Cannot convert 'UnityEngine.GameObject' to 'UnityEngine.Transform'.

I have the following code, and it is giving me the error: “Cannot convert ‘UnityEngine.GameObject’ to ‘UnityEngine.Transform’.” on the line with the GetComponent. I have no idea why because the variable lastPiece is set as a GameObject, but unity thinks its a Transform? Can anyone help?

var nextSnake : GameObject;
var lastPiece : GameObject;

function AddPiece()
{
	var newPart : GameObject = Instantiate(nextSnake, transform.position-(rigidbody.velocity * 100), Quaternion.identity);
	newPart.name = "Part";
	newPart.GetComponent.<SmoothFollow>().target = lastPiece;
	lastPiece = newPart;	
}

nextSnake likely is a var nextSnake : Transform in which case you can’t assign it to a gameobject. you would need to instantiate it and then get the related gameobject through .gameObject

Sorry, I forgot to post the var nextSnake… which is a GameObject.

What is SmoothFollow? What is target?

Smooth follow is a script attached to the object being created. Target is a variable on that script.
Its a script that comes with Unity.

If you take a look at the Smooth Follow script, Target is indeed a transform, and does not accept a GameObject.

var target : Transform;

So how would you recommend changing my code? Just changing the new object created to a transform?

Simply follow lastPiece’s transform:

newPart.GetComponent.<SmoothFollow>().target = lastPiece.transform;

Thank you so much :slight_smile: It works great

No problem, glad to have helped.

Thank you also, this just solved a problem that I was having, VERY similar. I was forgetting to add the “.transform” at the end of the line to let the engine know it is not the gameobject that I want it to follow per se, but it’s transform. Which is what the variable is defined as in the beginning of the script

4Years old but still helps…THANKS :smile: