I can't access the static variable in arrays.
Script:1
public class Test : MonoBehaviour
{
public List<GameObject> list;
public void value()
{
list[0].Test2.number+=100;
}
}
Script:2
public class Test2: MonoBehaviour
{
public static int number;
void Update()
{
if(number > 0)
{
Debug.Log(number);
}
}
}
I created a list, I want to access the zeroth element, I cannot access it. How do I access it with code.
Answer by The_Three_Vs · Mar 30, 2020 at 10:48 PM
EDIT: This is wrong, sorry. The correct solution is in my comment below.
To access classes/scripts of gameObjects, you need to use GetComponent first. So you would want to instead use list[0].GetComponent<Test2>().number += 100;
Hope this helps!
A 'static' variable does not 'belong' to individual gameObjects: it belongs to the class. If you have several gameObjects with a Test2 component, changing number in one will change number in all of them. Therefore, since number 'belongs' to Test2, you can skip accessing the list of gameObjects entirely and just use Test2.number += 100;
I want to assign the Test2 script value of the zeroth item. I just want to do this. Is there a solution to do this?
If that's the case, you need to delete the static keyword on number to make it an instance variable. Then you can edit the variables of individual objects with the technique in my original answer. If you want to have number be static, there is absolutely no way to access number in just the zeroth item.
Answer by mehmet067 · Mar 30, 2020 at 11:03 PM
list[0].GetComponent().number += 100; I tried that method but it didn't work
Your answer
Follow this Question
Related Questions
Change max range attribute? 0 Answers
Unity GetComponent Script? 1 Answer
if ( hit.collider.name == ("Exemple[0]") not working. is there a way to hit an array GameObjec? 0 Answers
Check through array list 1 Answer
How do I compare a gameobject's name to all strings in an arraylist [UnityScript] 0 Answers