I dynamically create objects in the scene, then go through an array to choose them. Choosen object is read.
Here’s my code:
using UnityEngine;
using System.Collections;
public class Chooser : MonoBehaviour {
[SerializeField] private int num;
[SerializeField] private GameObject[] objs;
public Material mat1;
public Material mat2;
public float timer;
void Start()
{
NextOne();
}
void Update()
{
if (Input.GetButtonUp("Fire1"))
{
NextOne();
}
}
void NextOne()
{
objs = GameObject.FindGameObjectsWithTag ("Player");
if (num >= objs.Length - 1)
num = 0;
else
num++;
foreach (GameObject obj in objs) {
obj.GetComponent <MeshRenderer> ().material = mat1;
}
objs [num].GetComponent <MeshRenderer> ().material = mat2;
Now, this what happens:
via GIPHY
As you can see, the choice of an object is always one step BEHIND. I need the latest (the one with the pointer) object to be RED. And it is always the last but one. What am I doing wrong?
(All my Spheres are tagged Player, this is how the script finds them).
Thanks.
GameObject.FindGameObjectsWithTag does not guaranty the return objects order of creation.
You should use a List and every time you create one add it to the list. This guarantees the order of the gameobjects.
Also if you only need the MeshRenderer of the GO, crate a List . Don’t use get component in for loops. they are performance heavy.
Similarly to the above, the array you create will always be unordered, so the last object will almost always be different.
Lists can work for this, however they can be somewhat slow when using the List.Contains method often.
I would recommend having a permanent array somewhere (if you’re going to be checking it often), then just resizing it when you want to add something else.
Resizing can also be somewhat CPU taxing if you’re doing it often, but slightly less so than using lists.
Here’s something I use to accomplish that (sorry if the syntax is wrong, I usually write JS):
void AddToArray(GameObject[] theArray, GameObject newObject){
GameObject[] tempArray = new GameObject[theArray.Length + 1];
for(int xx = 0; xx < theArray.Length; xx++){
tempArray[xx] = theArray[xx];
}
tempArray[tempArray.Length - 1] = newObject;
}