Ways to Unity 7: Global Scripts or Global Manager
The purpose
I just want to call a function every few seconds or minutes. How can do that?
The structure
You can just create an Empty Game Object
from the right-click in the Hierarchy window
.
Then attach a script to it.
For example, we rename the object to GlobalManager
, rename the script to Manager.cs
.
The code
Well, for javascript, it has a function called setTimeout()
.
For c# in unity, it has a function called InvokeRepeating()
.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
public GameObject[] animalPrefabs;
private float spawnRangeX = 20;
private float spawnPosZ = 20;
private float startDelay = 2;
private float spawnInterval = 1.5f;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("SpawnRandomAnimal", startDelay, spawnInterval);
}
// Update is called once per frame
void Update()
{
}
void SpawnRandomAnimal()
{
int animalIndex = Random.Range(0, animalPrefabs.Length);
Vector3 spawnPosition = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnPosZ);
Instantiate(animalPrefabs[animalIndex], spawnPosition, animalPrefabs[animalIndex].transform.rotation);
}
}
The thinking
I think c# is different across different places. For example, what you use to make a windows application is different than you would use in Unity game development.
The man who wrote this
https://yingshaoxo.blogspot.com/2020/12/ways-to-unity-7-global-scripts-or.html