Spawn and destroy gameObject by tag
I'm trying to make a function where a game object is destroyed and its position is used to spawn another game object. For details, my game have robots with multiple states of completion (from state0 to state3). Each state will enter an activator that is used to spawn the next state of completion as well as destroy the previous state(state0 enter activator, state1 is spawned, state0 is destroyed). The activator reads the game object's tag to verify whether it is the right state or not. The activator uses the previous state's position for the spawn position of the next position. The activator also only spawns and destroy when a key is pushed. Here is my code:`using UnityEngine; using System.Collections;
public class StateTransistorActivator : MonoBehaviour {
public KeyCode key;
bool active = false;
public GameObject initialState;
public GameObject transitionState;
GameObject robot;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(key) && active)
{
Instantiate(transitionState, robot.transform.position, Quaternion.identity);
Destroy(robot);
}
}
void OnTriggerEnter2D(Collider2D col)
{
active = true;
if (col.gameObject.tag == initialState.gameObject.tag)
{
Debug.Log("state0 is true");
robot = col.gameObject;
}
}
void OnTriggerExit2D(Collider2D col)
{
active = false;
}
The initialState variable is for the previous state game object which is used to compare the game object tag and the transitionState is used spawn the next state's game object.
This code works, but the problem I'm having is that i could not get it to work for multiple game objects of the same state. Basically if I have 2 game objects of the same state (clones of it) the activator only works for one of them, and I needed it to work in case for multiple similar game objects exists.
Here's some pictures
The purple thing is the state0, the rectangles are the activators.
The first robot transitioned correctly but no matter what I press the second one does not transitioned.
Your answer
Follow this Question
Related Questions
Spawn a random object on more than one position 1 Answer
Want to instantiate Prefab in its parent. 1 Answer
What is the most efficient way to spawn in a lot of cubes, like 10k? [c#] 2 Answers
How can I make an object clone in the time that I indicate it to appear? 0 Answers
Problem with Instantiated clones 1 Answer