【发布时间】: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方法。所以你需要一个PortalScript的instance 来调用该方法。看起来你的代码应该是,奇怪的是,Spawn.Spawn() -
谢谢 :) 这就是重点。
标签: c# unity3d reference gameobject