How do I get the the same variable from different instances of a script
I may be going around this the wrong way but I am trying to make a genetic algorithm really for fun it probably isn't needed but my fitness is being defined as the distance from an object however I don't know how to pass the variable of each instance of the gameobject to this breeder/natural selection script
Lets say you have two game objects (call them Object1 and Object2) defined in the inspector hierarchy.
Now lets say you have a class (we will call it $$anonymous$$yClass) with a variable called importantValue
defined like so
using UnityEngine;
using System.Collections;
public class $$anonymous$$yClass : $$anonymous$$onoBehaviour
{
public int importantValue;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
Now you would add this class to both game objects (Object1 and Object2). Now there are numerous ways to get theses values. In coded you could do this
int importantValue1 = GameObject.Find("Object1").GetComponent<$$anonymous$$yClass>().importantValue;
int importantValue2 = GameObject.Find("Object2").GetComponent<$$anonymous$$yClass>().importantValue;
Now this is just one way to get what you want.
So in this case the name is important ok thank you
I just use the above as an example. importantValue
might has well have been`xyz`. It is just a variable name, you did not specify anything or supply any code. What is important is that the variable is defined as public
.
As opposed to using GameObject.Find("ObjectsName")
I would recommend that you create a variable in your class to store a reference to the GameObject.
public GameObject object1;
This field will show up in the inspector, and allow you to drag any gameobject onto it. then use it like so:
sum+=object1.GetComponent<$$anonymous$$yClassWithImportantVariable >().importantValue;
Or, you can specify that you want only gameobjects with your script on it by simply specifying that class, rather than GameObject
public $$anonymous$$yClassWithImportantVariable object1;
Accessing the value inside start or update is even easier: e.g.
sum+=object1.importantValue;
Edit: I should also mention, using any of the above options, you will want to confirm the object actually exists, before trying to use it's variable, or you will get an nullReferenceException e.g.
if(object1)//confirms object exists
sum+=object1.importantValue;
Your answer
Follow this Question
Related Questions
Best way to generate meshes based on algebraic functions? 0 Answers
How to add programatically animationClips to one animation from Resources folder? 0 Answers
generating hallways using prefabs based on difficulty 1 Answer
How can I create a plane at any given vertex position? 0 Answers
How to generate assets along a vector3 0 Answers