- Home /
Making object switch between two tags every 3 seconds
how Can I make a script that makes an object switch between 2 tags every 3 seconds?
Answer by MarioSantoso · Apr 14, 2018 at 12:10 AM
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;
}
}
Answer by Bunny83 · Apr 13, 2018 at 07:35 PM
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";
}
}
Answer by shadowpuppet · Apr 13, 2018 at 06:24 PM
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;
}
}
Extremely bad solution because:
you should never call Start manually. In general you shouldn't call any Unity callback manually. It's bad practise in general.
What's the point of the boolean since you already check the tag?
The yield at the end has absolutely no effect beside keeping the coroutine one more frame alive.
Calling a coroutine recursively is in general a bad idea. Starting a coroutine generates garbage and has some overhead. Just use a loop.
for some reason a lot of times if I don't do the boolean things happen twice. Especially on cases of instantiating a ragdoll after death. I get two rags or even three unless I put a if dead false bool followed by setting it to true.