【问题标题】:How to reference an Object in Unity with C#?如何使用 C# 在 Unity 中引用对象?
【发布时间】:2020-03-08 17:43:42
【问题描述】:

嘿伙计们 我在以下代码中的 Unity 中收到错误 CS0120

错误 CS0120:非静态对象需要对象引用 字段、方法或属性“PortalScript.Spawn()”

脚本1:这里我尝试在屏幕上创建一个新的GameObject,与播放器有一定的距离。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;


public class PortalScript : MonoBehaviour
{
    public GameObject Portal; // referenced at Inspector
    GameObject Player = GameObject.Find("Player");

    public void Spawn()
    {
        bool portalSpawned = false;
        while (!portalSpawned)
        {   
            Vector3 portalPosition = new Vector3(Random.Range(-7f, 7f), Random.Range(-4f, 4f), 0f);
            if((portalPosition - Player.transform.position).magnitude < 3)
            {
                continue;
            }
            else
            {
                // Instantiate at position.
                Instantiate(Portal, portalPosition, Quaternion.identity);
                portalSpawned = true;
            }
        }
    }
}

脚本 2: 该脚本位于播放器上。在 Case 上,它应该从脚本 1 调用 Spawn 方法

public class Point : MonoBehaviour
{    

public PortalScript Spawn; 

    void Update()
        {
            score = updateScore;

            switch (score) 
            {
                case 1:
                    PortalScript.Spawn(); // ERROR at this line
                    break;
            }
}

如果我将脚本 1 中的代码直接写入脚本 2,它就可以工作。

我的大脑在这一点上停止了。感谢您的所有帮助,如果您需要更多信息,请告诉我。

【问题讨论】:

  • Spawn 不是static 方法。所以你需要一个PortalScriptinstance 来调用该方法。看起来你的代码应该是,奇怪的是,Spawn.Spawn()
  • 谢谢 :) 这就是重点。

标签: c# unity3d reference gameobject


【解决方案1】:

替换这一行:

PortalScript.Spawn(); // ERROR at this line

用这个:

Spawn.Spawn();

【讨论】:

  • 不过,这并不能回答问题。他将遇到 NullReferenceException,除非我没有看到其他内容。 Spawn 在哪里实例化?
  • @SotirisKoukios-Panopoulos 您不能(或不应该)实例化继承自 MonoBehaviour 自己的类。最好不要将MonoBehaviour 视为传统意义上的C# 对象。他们应该被认为是自己独特的东西。从技术上讲,它们是 Unity 所基于的实体组件系统架构的“组件”部分。
  • 那我很糟糕,我只在 C# 中思考,并没有完全了解 Unity 连接事物的方式
  • @0xBFE1A8 仍然可能发生,但如果 OP 没有通过 Inspector 引用 Spawn ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 2014-07-21
相关资源
最近更新 更多