- Home /
How to best optimise this script
Hi,
I have written a script which is used to fade out enemy objects that come within a specified distance from the camera. The script is to be used for iOS devices and I was wondering if anyone can recommend how I could optimise it to make it as light as possible on performance. It uses iTween.FadeTo() to fade the object.
I know that the distance check has to be run every frame and so must be inside the Update() function, but are there other areas I can improve on? The script is attached to the MainCamera.
Any help would be great.
//---
// Variable to hold the distance between the camera and the object
private float Dist;
// The distance at which the object will begin to fade
public float FadeDistance;
// The array of GameObjects (Enemies) in the scene that we want to be faded
public GameObject[] Enemies;
void Start()
{
// Find all of the object with tag "Enemy" in the scene and
// copy them into the Enemies array
Enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
void Update()
{
foreach (GameObject enemy in Enemies)
{
// If the element is null (false) the enemy is dead, so we ignore them
if (enemy)
{
// Find the distance between the Camera and the enemy getting its
// Absolute value (positive only)
Dist = Mathf.Abs(transform.position.z - enemy.transform.position.z);
// if the object has tag "enemy" AND is closer than our fade distance..
if (enemy.collider.tag == "Enemy" && Dist <= FadeDistance)
{
// Fade the object (level of alpha (0 = transparent), time to take to fade)
iTween.FadeTo(enemy, 0.0f, 0.2f);
// Destroy the enemy after 1 second
Destroy(enemy, 1);
}
}
}
}
Answer by FlyingOstriche · Aug 02, 2012 at 06:36 PM
Would it be faster to create a large sphere collider with FadeDistance radius around the camera. Then use 'is-trigger' to calculate when the enemy gets in fade range. (The enemies will go through the sphere collider if 'is-trigger' is on)
Then set it so that the Sphere collider only collides with the enemy layer.
Unity's collision code should be pretty optimized.
Your answer
Follow this Question
Related Questions
how to move or fade GUITextures with iTween 2 Answers
Fading out alpha on a 3d object with iTween 0 Answers
Optimization - Distance vs Collisions 3 Answers
Fade in object using iTween 0 Answers