How do I compare the same int in two different GameObjects?
Hi, is it possible to compare the same variable (there is a script with int a) in two different gameObjects public GameObject go1; public GameObject go2;
they both have the script and I did assign them in the #scene but whenever I try to state if(GO1.a == GO2.a)...
it tells me that neither one of them are defined. Is it possible for me to state it in another so that it works?
Answer by corn · May 23, 2016 at 08:14 PM
It seems you misunderstand how GameObjects work.
A GameObject is just an entity in a scene. By itself, it is pretty much useless, but its purpose is to hold Components, which are various objects you attach to a GameObject. Transform is a Component, it represents the GameObject's position in the scene space, a Sprite is a Component, a Renderer, a RigidBody... anything you attach to a GameObject is a Component. That includes the scripts you wrote.
So let's say you have a script with a public int attribute :
public class MyScript :
{
public int myInt = 0;
}
What happens when you attach it to a GameObject (myGameObject) ? It means that myGameObject will have a Component that is an instance of MyScript. But myGameObject won't magically get a myInt attribute, you cannot access this value directly from the GameObject. You need to get a reference to the MyScript Component that is attached to myGameObject, and then get the myInt attribute of said Component.
So here's your script with your two GameObjects :
public class CompareInts : MonoBehaviour
{
public GameObject go1;
public GameObject go2;
}
After you assign them in the scene, you have references to your two GameObjects, but you still can't read the myInt values. So the next step is to get references to their MyScript Components. For this, you need to use GetComponent.
So in MyScript, write :
private void Compare()
{
MyScript myScript1 = go1.GetComponent<MyScript>();
MyScript myScript2 = go2.GetComponent<MyScript>();
if (myScript1.myInt == myScript2.myInt)
{
// Whatever.
}
}
And then you have it, you got your two ints and you can compare them.
Thank you very much! You explained it in detail and I was able to understand it- you are the best!
You're welcome ! Don't forget to carefully read the Unity $$anonymous$$anual, you'll find very valuable information there. (:
Your answer
