Error CS0120 - Object reference required to access non-static member

Moved from Unity 4.6 to 5. Previously using JavaScript but now trying C#. Have tried to resolve this using information from answers to similar questions. Gather I need to be using GetComponent() but I cannot get it work.

An Object reference is required to access non-static member ‘UnityEngine.Rigidbody2D.velocity’

I suspect because of this, I am getting a further error:

Error CS0103: The name ‘Destroy’ does not exist in the current context.

This is the script:

using UnityEngine;
using System.Collections;

public class BetaProperties {

	// Allow access to variables in game manager script
	GameManager myGameManager = new GameManager ();

	private int CountCollisions = 0;
	private float ExistTimer = 0.0f;

	void Start () {
		// Launch particle in random direction at a given force
		UnityEngine.Rigidbody2D.velocity = Quaternion.AngleAxis (Random.Range (0, 360), Vector3.forward) * Vector3.up * 2;
	}

		// Start a counter
		void Update () {
			if (ExistTimer >= 0.0) {
				ExistTimer += Time.deltaTime;
			}
		}
		
		void OnCollisionEnter2D (Collision2D col) {
			// If collision is on a wall but less than 5 collisions, increase collision counter
			if ((col.gameObject.tag != "Wall") && (col.gameObject.tag != "Beta") && (CountCollisions < 5)) {
				CountCollisions ++;
			}
			// If collision is on wall with 5 or more collisions OR if colliding with another particle, destroy and add 50 to temperature
			else if (((col.gameObject.tag != "Wall") && (col.gameObject.tag != "Beta") && (CountCollisions >= 5)) || ((col.gameObject.tag == "Beta") && (ExistTimer >= 1))) {
				myGameManager.CurrentTemp = myGameManager.CurrentTemp + 50;
				Destroy(gameObject);
			}

	}

Please help if you can!

1 Answer

1

Your line:

UnityEngine.Rigidbody2D.velocity = Quaternion.AngleAxis (Random.Range (0, 360), Vector3.forward) * Vector3.up * 2;

should be:

GetComponent<Rigidbody2D>().velocity = Quaternion.AngleAxis (Random.Range (0, 360), Vector3.forward) * Vector3.up * 2;

where you get the reference to the Rigidbody2D component instance attached to your gameobject.

Thank you, this cleared up my Error CS0103 but had turned into Error CS0103 (The name 'GetComponent' does not exist in the current context). Through trial and error I realise this was because I hadn't declared MonoBehaviour!

–