user10469186
user10469186

Reputation:

Cannot apply indexing[] to an expression of type GameObject

I've got 3 empty Gameobjects in my scene that im trying to spawn objects on, i've written this script to have a RNG value between the spawners for the object to spawn.

I've run into a problem and im not too sure how to resolve it

public class Spawns : MonoBehaviour
{

public GameObject SpawnedObject;
public bool StopSpawn = false;
public float SpawnTime;
public float SpawnDelay;

public GameObject[] SpawnPoints;
int Randomint;

// Start is called before the first frame update
void Start()
{
    InvokeRepeating("SpawnObjects", SpawnTime, SpawnDelay);
}

public void SpawnObjects()
{
    Randomint = Random.Range(0, SpawnPoints.Length);
    Instantiate(SpawnedObject[Randomint], transform.position, transform.rotation);

    if (StopSpawn)
    {
        CancelInvoke("SpawnObjects");
    }
}
}

Upvotes: 0

Views: 98

Answers (1)

derHugo
derHugo

Reputation: 90872

You are trying to use an index on a single GameObject reference.

Since you pick the random value using SpawnPoints.Length and following your description you actually rather want to get an element of the array SpawnPoints instead.

Further you say

I've got 3 empty Gameobjects in my scene that im trying to spawn objects on

but that's not what your code would do.

You probably rather wanted to use

Instantiate(SpawnedObject, transform.position, transform.rotation, SpawnPoints[Randomint].transform);

See Instantiate and in your specific case the overload

public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);

The first parameter is the original prefab/object to spawn, the last parameter is the optional parent Transform where to spawn to.

You also might want to rethink your provided values for position and rotation .. do you really want to spawn the object at the position and rotation of the object your script is attached to? Would you not rather want them to get spawned at the position and rotation of the according spawn point? ;)

Upvotes: 1

Related Questions