Get transform of an instantiated GameObject(clone)

Hi, i have a problem with get the transform of an instantiated Gameobject(clone), i wanna get the trasform to use it in other script, i only achieve a null reference.

public class Enemy : MonoBehaviour {

	
	public float activeZone;
	float nextFire;
    public float Distance;
	public Transform player;
	public Transform FirePosition;
	 Transform enemy;
	GameObject Bullet;
	 Vector2 posPlayer;
	 Vector2 posBullet;

	
	
	void Start () 
	{
		nextFire = 0f;
		activeZone = 12f;
		player = GameObject.FindGameObjectWithTag ("Player").transform;
		FirePosition = GameObject.FindGameObjectWithTag ("Fire").transform;
		Bullet = GameObject.FindGameObjectWithTag("Bullets");

	}
	
	// Update is called once per frame
	void Update () 
	{

		if (Distance < activeZone) {
			
			if (Input.GetKeyDown (KeyCode.F) && Time.time > nextFire + 2.0f) {

				nextFire = Time.time;
				GameObject BulletInstance;
				BulletInstance = Instantiate (Bullet,FirePosition.position, FirePosition.rotation) as GameObject;
				BulletInstance.rigidbody2D.AddForce (new Vector2 (-5000f, -30f));
				enemy = BulletInstance.transform;
				Destroy(BulletInstance,0.5f);
			}	
		}
				
		}
		

	void FixedUpdate()
	{

		posPlayer = player.position;
		posBullet = FirePosition.position;
		Distance = Vector2.Distance (posPlayer, posBullet);
    }

It looks like enemy should be right - for 0.5 seconds anyway, after that it will be null.

–

yes, in that 0.5 seconds i wanna get the distance between the proyectile and the player, for the score, for now.

–

1 Answer

1

Try finding it directly after you instantiate it:

enemy = GameObject.Find(“Bullet(Clone)”).transform;

The OP has the object that they have already instantiated.

–

Thanks, but already got the problem, i added this two lines after instantiate, and problem solved, if(BulletInstance!=null) enemy = GameObject.Find ("Bullets(Clone)").transform; an evry time i want to use this clone(transform) first i have check if its not null.

–

There is no way you should be finding it like this. You are instantiating it. This code would never work properly if there were two or more bullets at once.

–

in the debug.log i get the actual position of the clone, maybe its not getting all the positions of all bullets, tomorrow will check it,

–