Parenting through my script isn't working. Why?

Hey fellows. Here’s some code:

var myTransform : Transform; // for caching

//var playfield : GameObject;

//playfield = new GameObject("Playfield");

var gameManager : GameManager; // used to call all global game related functions

var playerSpeed : float;

var horizontalMovementLimit : float; // stops the player leaving the view

var verticalMovementLimit : float;

var fireRate : float = 0.1; // time between shots

private var nextFire : float = 0; // used to time the next shot

var playerBulletSpeed : float;

//playfield = Playfield;


function Start () 


	myTransform = transform; // caching the transform is faster than accessing 'transform' directly

	myTransform.parent = Playfield.transform;


	myTransform.localRotation = Quaternion.identity;



function Update () 


	// read movement inputs

	var horizontalMove = (playerSpeed * Input.GetAxis("Horizontal")) * Time.deltaTime;

	var verticalMove = (playerSpeed * Input.GetAxis("Vertical")) * Time.deltaTime;

	var moveVector = new Vector3(horizontalMove, 0, verticalMove);

	moveVector = Vector3.ClampMagnitude(moveVector, playerSpeed * Time.deltaTime); // prevents the player moving above its max speed on diagonals


	// move the player

	myTransform.localPosition += moveVector;

If I try to compile this, I get this error:

An instance of type 'UnityEngine.Component' is required to access non static member 'transform'

Ok, fine. If I un-comment the 3rd and 4th lines, I can even get the darn thing to compile. And that little print line you see tells me that this object is parented to ‘Playfield (UnityEngine.Transform)’. Except that’s wrong somehow because the object does not follow my Playfield object, which is sitting nice and neat in the hierarchy with it’s own script that just scoots it off along the x axis.

Why is this not working. I’ve been banging at this for a week now. Save me.

I’m guessing the error is generated by this line:

myTransform.parent = Playfield.transform;

Only specific instances have a transform property, in your case you’re accessing the class Playfield and not a specific instance of that class.

Uncomment your playfield variable (line 3)

Add the following command to the beginning of your Start() method:

playfield = new GameObject("Playfield");

Then change the problem line to this:

myTransform.parent = playfield.transform;

Edit: Also, if you want to use an existing object instead of creating new ones (if you already have objects in the scene), then use this line instead:

playfield = GameObject.Find("Playfield"); // Playfield is the name of the game object in the scene