- Home /
variable increments multiple times !
i have a raycast that shoots from the center of the camera and in the forward direction , i have a parent object with 3 children objects , when the game starts it deactivate all children object and then set the first child active , when the ray hits the object an animation plays and then the next object gets activated , my problem is , to activate the next object im using indexes ( 0,1,2,3) , lets call x the index of the child object , when i do x++ from 0 it doesnt go to 1 and stops it goes to 2 then 3 and i get an child out of bounds error ... any solutions .
this is the script i am using
public class SelectObject : MonoBehaviour
{
// raycast variables
Vector2 touchPosition;
public float maxDistance = 10.0f;
public RaycastHit hits = new RaycastHit();
// Finding Components
public TextMeshProUGUI objectsFound;
public int FoundIndex ;
private Animator objectAnimator;
// Finding Process
private GameObject collector;
// Start is called before the first frame update
private void Awake()
{
collector = FindObjectOfType<RotateChildren>().gameObject;
}
void Start()
{
FoundIndex = collector.transform.childCount;
objectsFound.text = FoundIndex + "/4";
for (int i = 0; i < collector.transform.childCount; i++)
{
collector.transform.GetChild(i).gameObject.SetActive(false);
}
}
// Update is called once per frame
// the foundindex goes from 0 to number of children
void Update()
{
Debug.Log("Im here1");
Debug.Log(FoundIndex);
collector.transform.GetChild(FoundIndex).gameObject.SetActive(true);
Debug.DrawRay(transform.position, transform.forward * 10, Color.yellow);
Debug.Log("Im here2");
Debug.Log(FoundIndex);
if ( Physics.Raycast(transform.position, transform.forward, out RaycastHit hit) )
{
Debug.Log("HIT OBJECT");
GameObject go = hit.collider.gameObject;
StartCoroutine(FindingObject(go));
FoundIndex;
objectsFound.text = FoundIndex + "/4";
}
}
private IEnumerator FindingObject(GameObject go)
{
objectAnimator = go.GetComponent<Animator>() ;
objectAnimator.SetTrigger("Start");
yield return new WaitForSeconds(1.0f);
Debug.Log(" coroutine done ");
}
private void ChangeScale(GameObject go)
{
go.transform.localScale = new Vector3(2, 2, 2);
}
At row 50, where you do "FoundIndex;" is that correct? where do you increase X as you say?
Also are you sure you don't start the coroutine FindingObject many times before the first one has ended? StartCoroutine returns immediately before any of the coroutine has begun running. $$anonymous$$aybe objectAnimator shall be a local variable if you intend to start the coroutine many times.