I have this so far. I want create a script where if distance between planet and sun is less than 10 - color of planet become red, if it more than 10 - it become blue.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DistanceChecker : MonoBehaviour
{
public Transform sun;
public Transform planet;
public Renderer planetRender;
private float _distance;
private float distanceToChangeColor = 4f;
void CheckDistance()
{
_distance = Vector3.Magnitude(sun.transform.position - planet.transform.position);
}
void ChangeMaterialConditional()
{
if (_distance <= distanceToChangeColor)
{
planetRender.material.color = Color.red;
}
else
{
planetRender.material.color = Color.blue;
}
}
private void Update()
{
CheckDistance();
ChangeMaterialConditional();
}
I guess that calling methods CheckDistance
and ChangeMaterialConditional
in Update
its not a good idea.
If you need to execute code that controls rendering (looks) of your game then Update
is the best place to do that actually (as opposed to FixedUpdate
which is for physics and simulation). So no, that is not the problem.
To make sure Update
does not executes when your mesh is not visible on screen, add these two methods to switch Update
on/off automagically (note: this works when component is also accompanied by MeshRenderer
on the same GameObjec
).
void OnBecameVisible ()
{
enabled = true;
}
void OnBecameInvisible ()
{
enabled = false;
}
→ Unity - Scripting API: MonoBehaviour.OnBecameVisible()
→ Unity - Scripting API: MonoBehaviour.OnBecameInvisible()
Also, this code does the same while being shorter and easier to both read and understand:
using UnityEngine;
public class DistanceChecker : MonoBehaviour
{
public Transform sun;
public Transform planet;
public Renderer planetRender;
void Update ()
{
float distance = Vector3.Distance( sun.position , planet.position );
planetRender.material.color = distance<10f ? Color.red : Color.blue;
}
}
What you need to know is that accessing .material
property (planetRender.material
) creates a new Material
instance and can be potentially costly for rendering if you want to have a lot of objects like this. In such case a better solution will be to use shaders.