setting initial variable for base class from inherited class - class

I am a little rusty with C++ and am getting bogged down with what is probably a simple question, so apologies in advance.
I have created a child class from an existing library class and cannot work out how to set up an initial state for one of the base class functions.
Basically I have taken the sfml circleshape class and added a little of my own, but I would like to set the origin for all derived objects as a fixed number.
The base class takes 'name of class'.setOrigin(x,y) which is straightforward, but I want to know how to set this as a standard figure in all derived class instances. (basically my child class is called Ball and I have class Ball ball1, ball2 etc
This may make it clear what I have at the moment:
//derived class-----------------------------------------
class Ball : public sf::CircleShape
{
private:
int horiz,vert,rate,radius;
public:
void setHoriz(int hin)
{
horiz=hin;
}
int getHoriz(int hout)
{
hout=horiz;
return(hout);
}
void setVert(int vin)
{
vert=vin;
}
int getVert(int vout)
{
vout=vert;
return(vout);
}
//-----------------------------------------------
void setRate(int in)
{
rate=in;
}
int getRate(int out)
{
out=rate;
return(out);
}
//-----------------------------------------
};
So any advice on how to insert ' CircleShape.setOrigin ' into the Ball class would be appreciated. Thanks

Related

In Dart I'm trying to extend a class while changing the TYPE of one of its properties

Class1 has a property List<ClassA> xyz = [];. ClassA has a number of properties and methods. ClassB extends ClassA adding additional properties and methods. Is there a way for me to create Class2 extending Class1 but change the TYPE of xyz to List<ClassB>? If that is confusing hopefully code below will give an example of what I'm trying to accomplish. Basically the same as overriding a method but overriding a property.
class Game {
int points;
String opponent;
int opponentPoints;
}
class FootballGame extends Game {
int touchdowns;
int opponentstouchdowns;
}
class BaseballGame extends Game {
int homeruns;
int opponentsHomeruns;
}
class Team {
String name;
List<Game> games;
double winningPercentage() {
int wins = 0;
for(var game in games){
wins += (game.points > game.opponentPoints) ? 1 : 0;
}
return wins / games.length;
}
}
class FootballTeam extends Team {
// How do I change the TYPE of the games property to <FootballGame>
}
You could use the covariant keyword in this case:
class FootballTeam extends Team {
#override
covariant List<FootballGame> games;
}
However, be aware that doing so is potentially unsafe; the reason why you need the covariant keyword is to suppress the type error that arises because the override can violate the contract of the base class: the base class advertises that games can be assigned a List<Game>, but such an assignment would be invalid for the derived class. By using the covariant keyword, you disable the type-check and take responsibility for ensuring that you do not violate the contract in practice.
Note that if the games member were final (or were only a getter), then the override (which uses a more specific type) would be safe and wouldn't need to use covariant.
Edit
I had forgotten that I had written this answer when writing a more detailed answer for a similar question.

Unity Extension Method GameObject

I'm trying to add an extension method to my gameobject, that's works, but my problem is the GameObject share the same result. My goal is to have a different result for each GameObject.
// AddExtension.cs
public static class GameObjectExtensions
{
private static int life;
public static int Life(this GameObject gameObject)
{
return life;
}
public static void ChangeLife(this GameObject gameObject, int numberToAdd)
{
life += numberToAdd;
}
}
And in my main code, I would like to manage GameObject like :
void Start()
{
GameObject.Find("Perso0").ChangeLife(2);
GameObject.Find("Perso1").ChangeLife(4);
GameObject[] rootGOs = UnityEngine.Object.FindObjectsOfType<GameObject>();
foreach (GameObject g in rootGOs)
{
if(g.name == "Perso0")
{
Debug.Log("Perso0 : " + g.Life());
}
if(g.name == "Perso1")
{
Debug.Log("Perso1 : " + g.Life());
}
}
}
But both GameObject have 6 in "Life" ( 2 + 4 )
I whould like to get only 2 for "Perso0" with Life and 4 with "Perso1" with Life
Do you have some clue to helping me ?
Thank you and best Regards
Because your life variable is static, it's going to be the same value you're editing every time you call ChangeLife on a GameObject.
Since extension methods need to belong to static classes, and a static class can only have static members, you cannot achieve the goal you want with extension methods.
Even if you could, it's not the right way to go with the Unity paradigm. With this setup, you're essentially saying "Every GameObject in my scene has a life value," which I don't think you want to do.
Instead, you can create your own components, as below.
public class Enemy : MonoBehaviour
{
[SerializeField] private int _initialHealth = 100;
private int _health = -1;
public int health { get { return _health; } }
private void Awake()
{
_health = _initialHealth;
}
public void IncrementHealth(int health)
{
_health += health;
}
}
This is just an example, but you can make something to suit your needs.
static applied to a member means all instances share a single copy. That is, there's only one life variable, which is modified when you call ChangeLife() on any GameOject.
Since extension methods have to be in a static class, I don't think you can accomplish what you want this way.
However, you should be able to add custom properties to your players and other objects in Unity. I don't remember if they're called "custom properties" exactly, but I know some of the basic tutorials like Roll-a-Ball cover this (or at least used to).

String Constructor not working in unity c#

Salutations, this'll be brief.
So, I tried to change the name of one the hero struct in my game, but it doesn't update, neither in the inspector nor in the de facto code.
I can call the constructor just fine, and if I print the heroname before and after (in the constructor), it tells me the new name. However, It does not change.
Here is the (simplified) code:
//This already has a name in the inspector that I want to override
public List<TroopStat> PlayerHeroStats = new List<TroopStat>();
void Start () {
PlayerHeroStats[0].ChangeTroopType();
}
[System.Serializable]
public struct TroopStat {
public string nameOfTroop;
public void ChangeTroopType() {
nameOfTroop = "Blabla";
}
}
Any ideas?
Structs are value types. You need to assign a new struct or use class instead.
This should work:
void Start () {
TroopStat stat = PlayerHeroStats[0];
stat.ChangeTroopType();
PlayerHeroStats[0] = stat;
}
Or make the TroopStat a class.
You can read more about it here.

Unity Adding points to a user only once after collision

So I'm getting ready to create my first game, I just finished classes on the C# language so I apologize if I'm using stuff such as interfaces wrong and all that. However, for my question; I'm trying different things and seeing what works. I've created a coin, and a player. The coin works as it should, however sometimes when I collect it, it will give me twice the points it should. The coins value is 15, sometimes when I collect a coin it'll add 15 points, other times it will add 30. How do I prevent this from happening.
Here's my code:
Coin Controller Class:
public class CoinController : MonoBehaviour, IEconomy {
private int MoneyValue;
void Start () {
MoneyValue = 15;
}
void Update () {
}
void OnTriggerEnter(Collider col) {
if (col.CompareTag("Player")) {
Destroy(transform.gameObject);
Value();
}
}
public int Value() {
return EconomyController.Money += MoneyValue;
}
}
Economy Controller:
public class EconomyController : MonoBehaviour{
public static int Money;
void Start() {
Money = 0;
}
}
Economy Interface:
public interface IEconomy {
int Value();
}
I would like to point some things about your code:
A good practice when declaring variables is using lowerCamelCase:
thisIsLowerCamelCase
ThisIsNot
This is a variable name convention that is largely used in programming to differentiate Methods and Classes from variables.
Another thing I've noticed is that your "Money" variable is static and it is still being updated on your CoinController. I'd set this variable to be private int variable and use a setter to update it. With that in mind... Have you tried to use Debug.Log to check if the OnTriggerEnter is triggering twice before the object is destroyed?
Simply write:
Debug.Log ("This should only happen once!");
And play the game. If your console shows this message two times, this trigger is being called twice. Another thing that you might notice is that you are calling the Value () method after you called the Destroy (transform.gameObject).
I would do something like:
public class CoinController : MonoBehaviour{
private int moneyValue = 15;
private EconomyController economyController;
void Start (){
economyController = FindObjectOfType (typeof (EconomyController)) as EconomyController;
}
void OnTriggerEnter (Collider col) {
if (col.CompareTag("Player")) {
AddValue();
}
}
public int AddValue() {
EconomyController.money += moneyValue; //Option one.
EconomyController.AddMoney (moneyValue) ; //Option two.
DestroyGameObject ();
}
private void DestroyGameObject (){
Destroy(transform.gameObject);
}
}
Using the clean code principles, option 2 is using a public void function created inside the EconomyController class changing a private variable.
My intuition tells me that you are probably collecting two coins at the time. I'm not sure how you are setting out the coins but I've had a similar problem before.
Imagine a game of snake. Lets say you've programmed it so once you eat a square you create a new one to a random location. There is a probability that the new square would appear inside the snake so it would instantly be eaten. This could be why it happens only some of the time.
Try disabling the collider before you destroy it.
Destroying a gameobject isn't instant and it's (annoyingly) quite easy to set off triggers multiple times.
void OnTriggerEnter(Collider col) {
if (col.CompareTag("Player")) {
// Pseudo Code: GetComponent<TheColliderItIs>().Enabled = false;
Value();
Destroy(transform.gameObject);
}
}

How can I address a script I don't know the type of?

My game uses a variety of different game modes, and I'd like to spawn a different GameController script at the beginning of the scene depending on the game mode selected. Then other items (e.g., Enemies), would reference the main GameController, whether that be GameController_Mode1, GameController_Mode2, etc. But how can I have other objects referencing this if I don't know the type?
Unity iOS requires strict unityscript typing, so I can't use duck typing to get around this.
You can do this the same way you'd do it in C#, polymorphism. Derive all of your controllers from a single base Controller class. Then your GameController var can be set to any instantiation of a derived controller (see Start() in the example below).
Here is a quick example using a simple controller:
#pragma strict
var controller : MyController;
class MyController {
var data : int;
public function MyController(){
this.data = 42;
}
public function Print(){
Debug.Log("Controller: " + this.data);
}
}
class MyController1 extends MyController {
public function MyController1(){
this.data = 43;
}
public function Print(){
Debug.Log("Controller1: " + this.data);
}
}
class MyController2 extends MyController {
public function MyController2(){
this.data = 44;
}
public function Print(){
Debug.Log("Controller2: " + this.data);
}
}
function Start () {
controller = new MyController();
controller.Print(); // prints Controller: 42
controller = new MyController1();
controller.Print(); // prints Controller1: 43
controller = new MyController2();
controller.Print(); // prints Controller2: 44
}
I'm making any assumption that your gamecontrollers share function names and that the only difference is the code in each function.
[Update]
Regarding Heisenbug's comment below: You can use GetComponent to get the base class controller if your controller is a component.
Baseclass(BaseController.js):
class BaseController extends MonoBehaviour{
public function Print(){
Debug.Log("BaseController");
}
}
Extended class(Controller1.js):
class Controller1 extends BaseController {
public function Print(){
Debug.Log("Controller1: " + this.data);
}
}
Test:
var controller : BaseController;
controller = gameObject.GetComponent("BaseController"); //.GetComponent(BaseController) also works
controller.Print(); // will print "Controller1" if actual attached component is a Controller1 type
While it looks like there are some good answers already but it is worth mentioning Unity's SendMessage system. It is a really simple approach if all you need to do is call functions on the other object SendMessage.
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.SendMessage.html
In short you can use the following syntax:
TargetGameObject.SendMessage("targetFunction", argument, SendMessageOptions.DontRequireReceiver);
You can also use SendMessage to call javascript functions from C# scripts or vice versa.