I will teach you how to create vast optimization within a Unity game using C# scripting and will cover the topics listed below:
- No prefabs
- Distance method
Prefabs require more reading than a regular model and will use more memory, reducing your in-game frame rate. You can construct prefabs with code and this way your frame rates will be drastically higher. No problems adding thousands of game objects with components included. I have provided an example of constructing a prefab with code:
using UnityEngine;
public class NoPrefabs : MonoBehaviour
{
public GameObject[] fruits;
public int amountOfFruits = 10000;
public int volume = 25;
void Start()
{
//Load resources
fruits = new GameObject[2];
fruits[0] = Resources.Load("Models/Apple") as GameObject;
fruits[1] = Resources.Load("Models/Banana") as GameObject;
//Instantiate amount of fruits
for (int i = 0; i < amountOfFruits; i++)
{
Instantiate();
}
}
void Instantiate()
{
//Instantiate
GameObject fruit = fruits[Random.Range(0, fruits.Length)];
GameObject instantiatedFruit = Instantiate(fruit);
//Do stuff here
//Preferences
instantiatedFruit.GetComponent<Renderer>().castShadows = false;
instantiatedFruit.GetComponent<Renderer>().receiveShadows = false;
//Transform
instantiatedFruit.transform.position = new Vector3(Random.Range(-volume, volume), Random.Range(-volume, volume), Random.Range(-volume, volume));
instantiatedFruit.transform.rotation = Quaternion.Euler(Random.Range(0, 360), Random.Range(0, 360), Random.Range(0, 360));
float scale = Random.Range(1, 3);
instantiatedFruit.transform.localScale = new Vector3(scale, scale, scale);
//Renderer
instantiatedFruit.transform.GetComponent<Renderer>().material = Resources.Load("Materials/Fruit") as Material;
//Components
instantiatedFruit.AddComponent<DistanceMethod>();
}
}
You can with the distance method disable scripts within a certain distance, increasing frame rates drastically.
using UnityEngine;
public class DistanceMethod : MonoBehaviour
{
float distance;
float cancelDistance = 7;
void Update()
{
//Get distance
distance = Vector3.Distance(Camera.main.transform.position, transform.position);
//Within distance
if (distance <= cancelDistance)
{
if (GetComponent<Renderer>().material.color != new Color(0, 1, 0))
{
GetComponent<Renderer>().material.color = new Color(0, 1, 0);
}
}
else
{
if (GetComponent<Renderer>().material.color != new Color(1, 1, 1))
{
GetComponent<Renderer>().material.color = new Color(1, 1, 1);
}
}
}
}
The example shows fruits turning green only when in distance. You may choose to check for enabled/disabled components and enable/disable them instead