CS0120: An object reference is required to acces non-static member 'UnityEngine.Component.transform'
Unity give me this error...
============ Player.cs ============
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public static float speed = 4.0f;
public static int life = 3;
public static int score = 0;
public static bool canFire = true;
void Start () {
}
void Update () {
}
public static void Move(string direction){
if (direction == "UP") {
transform.Translate (Vector2.up * Player.speed * Time.deltaTime);
}
if (direction == "DOWN") {
transform.Translate (Vector2.down * Player.speed * Time.deltaTime);
}
if (direction == "LEFT") {
transform.Translate (Vector2.left * Player.speed * Time.deltaTime);
}
if (direction == "RIGHT") {
transform.Translate (Vector2.right * Player.speed * Time.deltaTime);
}
}
}
=================== ButtonManager.cs ===================
using UnityEngine;
using System.Collections;
public class ButtonManager : MonoBehaviour {
public Sprite ShipButtonDown;
public Sprite ShipButtonUp;
void OnMouseDown(){
this.gameObject.GetComponent<SpriteRenderer> ().sprite = ShipButtonDown;
if (gameObject.name == "ShipButtonUp") {
Player.Move ("UP");
} else if (gameObject.name == "ShipButtonDown") {
Player.Move ("DOWN");
} else if (gameObject.name == "ShipButtonLeft") {
Player.Move ("LEFT");
}
else if (gameObject.name == "ShipButtonRight") {
Player.Move ("RIGHT");
}
}
void OnMouseUp(){
this.gameObject.GetComponent<SpriteRenderer> ().sprite = ShipButtonUp;
}
}
Answer by corn · Jan 04, 2016 at 09:42 PM
Move is a static method. When you use Player.Move, you're not working with your instance of Player, which is attached to a GameObject and thus has a transform. When using a static method, there is no object involved at all, it is not attached to any GameObject, so you cannot use transform in that method.
So Move cannot be static, you must change that in Player.cs.
Now there are two solutions to make ButtonManager work. Either you get a reference to your Player (by assigning it in the editor, or with a FindObjectOfType) or you use the Singleton pattern, which seems to be exactly what you wanted to do.
Your answer
Follow this Question
Related Questions
how to fix cs1014 error 1 Answer
Missing ',' when there is no need? 0 Answers
only using GetMouseButtonDown(0) once 0 Answers
I need help working out a C# script with error CS0120 1 Answer
Bugs on my C# Scripts? 0 Answers