- Home /
Sending out coordinates
I want an enemy to send out its position when it dies so that another object can decide if it will create a power up at the death point, or not.
My code is:
enemyPlace = GameObject.Find("Signal");
if (enemyPlace == null)
print("null");
if (enemyPlace != null)
{
print("Found the signal");
SpawnPowerUp (hasSpawned,playerGot,kills);
}
The problem is, though, that it keeps returning the null, even when there are signals instantiated. (the object's name is signal, and they stay in the scene until SpawnPowerUp is executed)
Answer by duck · Mar 30, 2010 at 07:39 PM
Rather than using GameObject.Find, it might be better to consider passing a message directly from your enemy to the powerup manager.
Eg, assuming your powerup manager script is called "PowerupManager", and is placed on an empty gameobject in the scene, you could use this in your enemy script:
var powerupManager : PowerupManager;
function Start() { // when the enemy starts, it locates the instance of the powerup manager powerupManager = FindObjectOfType(PowerupManager); }
function Kill() { // this enemy just died
// tell powerup manager:
powerupManager.NotifyDeath(transform.position);
// remove the enemy gameobject
Destroy(gameObject);
}
Then, in your PowerupManager script:
GameObject powerupPrefab;
function NotifyDeath(diePosition : Vector3) { // 1 in 10 chance of a powerup appearing: if (Random.value > 0.9) { Instantiate(powerupPrefab, diePosition, Quaternion.identity); } }
Doing it this way means you don't have to do any 'finding' objects in order to pass information while your game is running. Each enemy only does a 'find' once when it's initially instantiated, which is much better for performance, and also for a clean structure to your game system's inter-communication.
For more information about this, see "Communication between objects and other scripts".
Your answer
Follow this Question
Related Questions
How to do a check if an Array is empty? 2 Answers
Null Scripts 1 Answer
Null Reference Exception Error 1 Answer
3rd person controller NullReferenceException 2 Answers
Getting NullReference when calling Instantiate from another script 0 Answers