how Can I make a script that makes an object switch between 2 tags every 3 seconds?
The easiest and most straight forward solution would be using a coroutine like this:
void Start()
{
StartCoroutine(ChangeTag());
}
IEnumerator ChangeTag()
{
var wait = new WaitForSeconds(3);
while (true)
{
yield return wait;
gameObject.tag = "tag1";
yield return wait;
gameObject.tag = "tag2";
}
}
Since no one has answered I’ll take a stab at it. May not be the best answer but at the moment it is the only answer. I would use a coroutine.
using UnityEngine;
using System.Collections;
public class testSwap : MonoBehaviour {
public bool changed;
void Start() {
changed = false;
Debug.Log ("start");
StartCoroutine(ChangeTag());
}
private IEnumerator ChangeTag(){
yield return new WaitForSeconds(3);
if (gameObject.tag == "tag2"&& changed == false) {//one of your tags to toggle
gameObject.tag = "tag1"; //the other tag you want to toggle
changed = true;
Debug.Log ("now tag1");
}
if (gameObject.tag == "tag1" && changed == false) {
gameObject.tag = "tag2";
Debug.Log ("now tag2");
changed = true;
}
Start ();
yield return null;
}
}
Assign this script and play, you should have what you want, don’t forget to change interval.
using UnityEngine;
public class ChangeTag : MonoBehaviour
{
public float interval;
public string[] tags;
private float _timer;
private int _tagID = 0;
void Update()
{
if (_timer >= interval)
{
_timer = 0;
gameObject.tag = tags[_tagID];
_tagID++;
if (_tagID > tags.Length)
_tagID = 0;
}
else
_timer += Time.deltaTime;
}
}