Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Unity 5非静态字段、方法或属性错误需要对象引用_C#_Class_Oop_Unity5_Instantiation - Fatal编程技术网

C# Unity 5非静态字段、方法或属性错误需要对象引用

C# Unity 5非静态字段、方法或属性错误需要对象引用,c#,class,oop,unity5,instantiation,C#,Class,Oop,Unity5,Instantiation,在Unity 5中,在我的PlayerMovement类的第35行使用c#时,我有以下错误: 错误CS0120非静态字段需要对象引用, 方法或属性“GameManager.completeLevel()” 玩家移动等级: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public Ga

在Unity 5中,在我的PlayerMovement类的第35行使用c#时,我有以下错误:

错误CS0120非静态字段需要对象引用, 方法或属性“GameManager.completeLevel()”

玩家移动等级:

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对象

public GameObject gameManager;
Instantiate(gameManager)
或者正如Jim提到的:

您需要将completeLevel标记为静态:

更多信息请参见:

由于您的
GameManager
类继承自
MonoBehavior
,因此需要将此脚本附加到游戏对象。然后您需要获得对
GameManager
组件的引用,这可以通过多种方式完成

GameManager GameManager=GameObject.Find(“GameManager”).GetComponent()

如果您的游戏对象名为“GameManager”,则上述操作有效。如果您的游戏对象名为其他对象,请将其替换为您的对象名

然后
GameManager.completeLevel()现在可以工作了

你可以把这个缩短到
GameObject.Find(“GameManager”).GetComponent().completeLevel()


如果GameManager脚本附加到与PlayerMovement相同的游戏对象上,那么这就是您所需要的全部
GetComponent().completeLevel()

var gm=new GameManager()在哪里?
public GameObject gameManager;
Instantiate(gameManager)
static public void completeLevel()
{
    ....
}