Cannot implicitly convert type `UnityEngine.Object' to `UnityEngine.Transform'.

I have this code

public Transform[] currentBullet;

void Functionname(){
currentBullet[i] = Instantiate(theBullet, muzzlePos.position, muzzlePos.rotation);
        i++;
}

And im getting this errorAssets/Script/damageTowers/turret.cs(70,17): error CS0266: Cannot implicitly convert type `UnityEngine.Object' to `UnityEngine.Transform'. An explicit conversion exists (are you missing a cast?)

What is wrong?

You need to cast the result of instantiate to GameObject, and then reference its transform.

Also, I’d suggest using a List instead of an array, unless you’ve set it up somewhere that the array length represents the maximum number of current bullets.

Like so:

List<Transform> currentBullets = new List<Transform>();

void CreateBullet() {
     var bulletInstance = Instantiate(bulletPrefab, muzzle.position, muzzle.rotation) as GameObject;
  
     currentBullets.Add(bulletInstance.transform);

}

Lets say i want to remove the list/array and it only has to be 1 transform/gameobjec,t how do i do that?

then don’t use an Array at all!

Transform currentBullet;

void CreateBullet() {
     currentBullet = (Instantiate(bulletPrefab, muzzle.position, muzzle.rotation) as GameObject).transform;
}

Thanks :wink:

1 Like

Apperently the instantiate object wont be “saved” in CurrentBullet. why?

I get the error

NullReferenceException: Object reference not set to an instance of an object
turret.FireProjectile () (at Assets/Script/damageTowers/turret.cs:69)

Found the problem :wink:
I should change GameObject to Transform

from

currentBullet = (Instantiate(bulletPrefab, muzzle.position, muzzle.rotation) as GameObject).transform;

to

currentBullet = (Instantiate(theBullet, muzzlePos.position, muzzlePos.rotation) as Transform).transform;