- Home /
Calling a variable from a spawner with multiple spawners
So my game with have 4 spawners. One for each cardinal direction. They spawn cubes they should move toawrds the center. The spawners are different in that I have a string so I can name then North, South,etc. When I spawn the cubes I need a velocity based on the string. I need the cube to know which spawner it came from. I don't know how to do this. I think I need to call the spawn script from the script thats on the spawned cube?
using UnityEngine;
using System.Collections;
public class directionalSpawner : MonoBehaviour {
public string Direction;
public GameObject Cube;
public Vector2 velo;
private string key;
// Use this for initialization
void Start () {
switch (Direction)
{
case "North":
velo = new Vector2(0.0f,-10.0f);
key = "W";
break;
case "South":
velo = new Vector2(0.0f, 10.0f);
key = "S";
break;
case "East":
velo = new Vector2(-10.0f, 0.0f);
key = "D";
break;
case "West":
velo = new Vector2(10.0f, 0.0f);
key = "A";
break;
}
StartCoroutine (Spawn ());
}
// Update is called once per frame
void FixedUpdate () {
}
IEnumerator Spawn(){
while (Input.GetKeyDown(key)) {
Vector3 spawnPosition = new Vector3 (gameObject.transform.position.x, gameObject.transform.position.y, 0.0f);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (Cube, spawnPosition, spawnRotation);
Cube.rigidbody2D.velocity = velo;
yield return new WaitForSeconds (1.0f);
}
}
}
Answer by hav_ngs_ru · Dec 25, 2014 at 04:53 PM
The first way (you need to declare public field in script attached to cube):
newCube.GetComponent().somePublicFieldInCubeController = key;
The sesond way (you need make a function to accept string data from anybody):
newCube.SendMessage("SetSpawnerKey", key); // this will call SetSpawnerKey(string key) in cube controller
and one more - you should store reference tou your cube object to interact with it! In your code your Cube is reference to prefab, not to object was created. Fix it like this:
GameObject newCube = Instantiate (Cube, spawnPosition, spawnRotation);
newCube.rigidbody2D.velocity = velo;
...
Your answer
Follow this Question
Related Questions
Zombie Spawner Not Spawn Zombies 1 Answer
Activate a script if an object is in the game world? 4 Answers
My Spawner Spawns Forever until Unity Crashes 2 Answers
Odd player teleporting 0 Answers
Enemy Spawner based on enemies values ! 0 Answers