c# - How to modify List<> between two classes in unity? -
in unity i'm making program allows click on cube , select spheres represent vertices shown below:
once theses spheres selected added list selectedspheres of type gameobject.
i've created 2 class files - cube.cs , vertex.cs. vertex inherits cube inherits monobehaviour. in cube have member list stores selected spheres.
i have defined function addtoselected() adds input selectedspheres list. print statement inside function prints off true every single time. print statement in update() function prints argument out of range error shown below while addtoselected() has shown has worked 8 times:
the addtoselected() function called onmousedown() function inside vertex class. code both classes shown below:
cube.cs
public class cube : monobehaviour { bool isselected = false; gameobject[] spheres; list<gameobject> selectedspheres = new list<gameobject>(); public void addtoselected(gameobject obj) { selectedspheres.add(obj); print(selectedspheres.contains(obj)); } public void removeselected(gameobject obj) { selectedspheres.remove(obj); } public void clearselected() { selectedspheres.clear(); } // update called once per frame void update() { if(input.getkeydown(keycode.space)) { print(selectedspheres[0]); } } } vertex.cs
public class vertex : cube { void onmousedown() { // object clicked - renderer rend = getcomponent<renderer>(); if (rend.material.color != color.red) { rend.material.color = color.red; // #d96459 addtoselected(this.gameobject); } else { rend.material.color = color.white; removeselected(this.gameobject); } } }
since vertex inherits form cube , cube has update function
void update() { if(input.getkeydown(keycode.space)) { print(selectedspheres[0]); } } the statement print(selectedspheres[0]); executed inside of objects inherit cube everytime press space key. in (or most) instances of vertex selectedspheres empty, why argument out of range error. also, have defined selectedspheres list every instance of cube (and therefore vertex). have 9 instances of selectedspheres in sample scene. shortest way fix declare selectedspheres static. then, have 1 list instances of cube/vertex.
so go ahead , try:
static list<gameobject> selectedspheres = new list<gameobject>(); 

Comments
Post a Comment