Remmember the spawner

I asked this question before and I didn’t get any answer or a tip for some days. I can’t continue building the game without it:

I made some helicopters which spawns whenever another helicopter is destroyed. The helicopter follow me from above and when its run out of ammo it should fly back exactly to where it spawned. For this, I put a tag on some objects which can spawn them.

the problem is that when the helicopter spawns it can’t choose the object that spawned it because I have many of them. The code works fine when I have only one object that can spawn helicopters.

After I got an answer there I got these two codes:

on the spawner:

var chopper : Transform;
var spawnPoint : Transform;
var spawningEffect : Transform;
var isAlive = false;

function Update ()
{
   if(!isAlive)
   {
      Spawn ();
   }
}

function Spawn ()
{
   isAlive = true;
   var effect = Instantiate (spawningEffect, spawnPoint.transform.position, Quaternion.identity);
   yield WaitForSeconds (4.0);
   var spawnChopper = Instantiate (chopper, spawnPoint.transform.position, Quaternion.identity);
   spawnChopper.SetSpawner(this);
}

On the helicoper:

var landingPlate;

function SetSpawner (spawner : GameObject)
{
   landingPlate = spawner;
}

I’m getting this error: NullReferenceException: Object reference not set to an instance of an object.

What is the problem?

The “this” keyword references the script it is written inside of, not the GameObject.

//Change the code in spawner to this
spawnChopper.SendMessage ("SetSpawner", this.gameObject);

You included way too less information. We don’t know how you spawn the chopper, also we don’t know what spawnChopper is actually referencing, the spawner, or the spawnedChopper?

I would do something like this:

//Chopper.js
public var mySpawner : Spawner;

function Update()
{
    // chopper stuff
    if (ShouldFlyBack)
        FlyTo(mySpawner.transform.position);
}

//Spawner.js

public var chopperPrefab : Chopper;  // assign in the inspector

function Spawn()
{
    var clone : Chopper = Instantiate(chopperPrefab, transform.position, transform.quaternion);
    clone.mySpawner = this;
}

Now you can always reference back to the spawner script (and it’s gameobject / transform) whenever you want by using the mySpawner reference in the chopper.

If you don’t like this as public variable, you can make it private and create a setter:

//Chopper.js
private var mySpawner : Spawner;

function SetSpawner(aSpawner : Spawner)
{
    mySpawner = aSpawner;
}

function Update()
{
    // chopper stuff
}

//Spawner.js

public var chopperPrefab : Chopper;  // assign in the inspector

function Spawn()
{
    var clone : Chopper = Instantiate(chopperPrefab, transform.position, transform.quaternion);
    clone.SetSpawner(this);
}