In Unity 5 using c# on line 35 of my PlayerMovement class I have this error:
Error CS0120 An object reference is required for the non-static field, method, or property 'GameManager.completeLevel()'
PlayerMovement Class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public GameObject deathParticals;
public float moveSpeed;
private Vector3 spawn;
// Use this for initialization
void Start () {
spawn = transform.position;
moveSpeed = 5f;
}
// Update is called once per frame
void Update() {
transform.Translate(moveSpeed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, moveSpeed * Input.GetAxis("Vertical") * Time.deltaTime);
if (transform.position.y < -2)
{
Die();
}
}
void OnCollisionStay(Collision other)
{
if (other.transform.tag == "Enemy")
{
Die();
}
}
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Goal")
{
GameManager.completeLevel();
}
}
void Die()
{
Instantiate(deathParticals, transform.position, Quaternion.identity);
transform.position = spawn;
}
}
GameManager Class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public static int currentScore;
public static int highscore;
public static int currentLevel = 0;
public static int unlockedLevel;
public void completeLevel()
{
currentLevel += 1;
Application.LoadLevel(currentLevel);
}
}
As your
GameManager
class inherits fromMonoBehaviour
, this script needs to be attached to a game object. Then you need to get a reference to the theGameManager
component, which can be done in several ways.GameManager gameMananger = GameObject.Find("GameManager").GetComponent<GameManager>();
The above will work if your game object is called "GameManager", swap this for the name of your object if it is called something else.
Then
gameMananger.completeLevel();
will now work.You could shorten this to
GameObject.Find("GameManager").GetComponent<GameManager>().completeLevel();
If the GameManager script is attached to the same gameObject as PlayerMovement, this is all you need
GetComponent<GameManager>().completeLevel();