Hy Guys I'm getting the error CS0120 in Unity at following Code:
Error CS0120: An object reference is required for the non-static field, method, or property 'PortalScript.Spawn()'
Script 1: here I try to create a new GameObject
on Screen with a certain distance to Player.
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;
}
}
}
}
Script 2: This script is on the Player. On Case it should call the method Spawn from script 1
public class Point : MonoBehaviour
{
public PortalScript Spawn;
void Update()
{
score = updateScore;
switch (score)
{
case 1:
PortalScript.Spawn(); // ERROR at this line
break;
}
}
If I write the code from script 1 directly into script 2, it works.
My brain stops at that point. Thanks for all your help and let me know if you need more information.
Spawn
is not astatic
method. So you need an instance ofPortalScript
in order to call that method. It looks like your code should be, oddly enough,Spawn.Spawn()
- Zer0