Jason94
Jason94

Reputation: 13620

How can I pass a object to an instantiated object?

I'm creating a game where there is a turret shooting down objects, and only if they are in range... at least that is the thought.

Right now I'm able to detect the object distance, and if it is close enough the turret will fire a bullet:

            if( distanceToTarget < 10 )
            {
                Instantiate(Bullet, transform.position, new Quaternion());
            }

The only problem is that the Bullet has no target. On the script (C#) of the Bullet i have defined a public GameObject Target that should hold the target. But how can I set this? Because when I instantiate the bullet, i know the target. Regularly I would set it straight forward, something like Bullet.Target = target, but I'm new to Unity and can't see how to set properties of a game object I Instantiate. The script of the Bullet would then check if the target exists, ifnot destroy it self, ifso travel to target :)

But how can I set it's target?

Upvotes: 1

Views: 508

Answers (2)

toreau
toreau

Reputation: 660

It seems to me that you are overcomplicating things, in that you seem to want to steer the bullet. I don't know how your turret works, but most turrets I have seen in games will start following the target when it's in view, and then start shooting at it when it's close enough.

Pseudo-ish, something like this:

void Update () {
    if ( canSeeTarget() ) {
        rotateToTarget();

        if ( targetInRange() ) {
            startShooting();
        }
    }
}

Upvotes: 0

bundz
bundz

Reputation: 11

This Instantiate function returns the instantiate object. All you need to do is:

if( distanceToTarget < 10 )
    {
        GameObject obj = (GameObject) Instantiate(Bullet, transform.position, new Quaternion());
        obj.GetComponent<Bullet>().Target = target;
    }

Upvotes: 1

Related Questions