Object spawn at spawn points
Hello!
I want to make a spawn points on or in the furnitures(desk,chair,closet,etc) and make the objects spawn randomly.
There will be like 9 spawn points.
The objects don't need a random Z( if Z is random, then the objects are gonna float from the furnitures).
Help me plz!
Answer by Hellium · Feb 13, 2018 at 09:16 AM
Create a new Empty gameobject,
Create a new script called
Spawner
and copy-paste the following codeIn your scene, create new empties and drag & drop them in the
spawnPoints
array in the inspector of theSpawner
componentGet a reference to the
Spawner
script (using public attribute to your own class, or by usingFindObjectOfType<Spawner>()
and call thePlaceTransform
function
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour
{
[SerializeField]
private System.Collections.Generic.List<Transform> spawnPoints;
private System.Collections.Generic.List<Transform> availableSpawnPoints;
private void Awake()
{
availableSpawnPoints = new System.Collections.Generic.List<Transform>(spawnPoints);
}
public void PlaceTransform( Transform transformToPlace )
{
if (availableSpawnPoints.Count > 0)
{
int index = Random.Range(0, availableSpawnPoints.Count);
transformToPlace.position = availableSpawnPoints[index].position;
availableSpawnPoints.RemoveAt(index);
}
else
{
Debug.LogError("No spawn point available");
}
}
}
Thanks for helping. But I can't understand after 3.
I made a Spawner script.
And I put the empty gameobjects on the place where I'm trying to use as spawn points.
But I got stuck after that.
Can you explain with a photo??
Supposing you have a script responsible for managing your items you want to place randomly:
using UnityEngine;
using System.Collections;
public class $$anonymous$$yItems$$anonymous$$anager : $$anonymous$$onoBehaviour
{
// Drag & drop the gamobjects to place randomly
[SerializeField]
private Transform[] objectsToPlace ;
// Drag & drop the gamobject with the `Spawner` script
[SerializeField]
private Spawner spawner ;
private void Start()
{
for( int i = 0 ; i < objectsToPlace.Length ; ++i ) spawner.PlaceTransform( objectsToPlace[i] ) ;
}
}