Reputation: 37
I have 7 game objects or more. I want to run only one gameObject after the other. Starting with Gameobject 0 --> GameObject 1 --> GameObject 2. At the moment my script activates a new object each time Space is pressed, and the old ones are not deactivated.
Thanks for your help!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ToggleTest : MonoBehaviour
{
public GameObject[] objects;
public int objCount = 0;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
objCount += 1;
objects[objCount].SetActive(true);
}
}
}
Upvotes: 3
Views: 263
Reputation: 904
If I understand your question correctly, try this:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ToggleTest : MonoBehaviour
{
public GameObject[] objects;
public int objCount = 0;
private float smallDelay = 0.1f;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && smallDelay <= 0)
{
objCount += 1;
objects[objCount].SetActive(true);
objects[objCount-1].SetActive(false); // this is only if you want to deactivate the previous object.
smallDelay = 0.1f;
}
smallDelay -= Time.DeltaTime;
}
}
This is not a perfect code, but because your function's if statement is one the Update()
method, I think it needs a little delay. You can also change the smallDelay to a bigger number.
EDIT
This is the answer on your comment:
if (objCount == objects.Length)
{
objCount = 0;
object[objCount].setActive(false);
object[0].setActive(true);
}
add this in the if statement or somewhere else in the Update().
Upvotes: 2