How to check transform.localscale in if statement.

I’m just setting up a simple script to increase vegetation over time and I’m wondering what the correct syntax to use in the if statement.

Everything works without the if statement. I just want to add it in so if its scale is <= 2 the script shuts off and the plant stops growing. Should be the only line I need help with.

var plant : Transform;
var speed : float = 1;

function Update () {
//
transform.localScale += Vector3.one * speed * Time.deltaTime * .01;

if(transform.localScale <= 2){   //This is what I need to correct
        Debug.Log("Done");
}
}

Temporary Fix
Well, I’d rather be able to tell when the transform was at a certain size to cancel the script but for now I just stuck a timer on it to shut down the script. Downside is I have to calculate how much time will pass before it gets to its full grown size which wastes a bit of time.

var plant : Transform;
public var counter : float = 0;
var speed : float = 1;


function Start () {
  doneGrowing = false;
}



function Update () {

transform.localScale += Vector3.one * speed * Time.deltaTime * .01;
    counter++;
   
    if(counter > 1000){
        doneGrowing = true;
        counter = 0;
        StartCoroutine("Kill_Script");
        }
}

    function Kill_Script(){
    GetComponent("Plant_Growth").enabled = false;
    }

You are trying to compare it to a int, you should be comparing to a vector3. if all the scales are the same, you could transform.localScale.x for example.

2 Likes

You probably want to just use any one of the three numbers in the scale to compare. e.g. transform.localScale.x

If you want to take into account all three numbers, you can use transform.localScale.magnitude. Note that this won’t give you a value of 1 for (1,1,1), but (if I recall my formulas correctly) the cube root of 3, as it’s basically going to give you the distance from (0,0,0) to (1,1,1).

If you are doing this a lot (e.g. hundreds of times per frame), you will want to optimize it; .magnitude is a pretty slow operation because it has to calculate a square root. You can use .sqrMagnitude, which returns the magnitude squared. This is useful because this

if (transform.localScale.sqrMagnitude < 2*2)

is MUCH faster than this:

if (transform.localScale.magnitude < 2)
2 Likes

Gah, I knew it was something simple. Worked like a charm zombie. (still learning the simple stuff lol)

Ah, I didn’t know about this. I’m going to take this into consideration and adopt my code appropriately!

@zombiegorilla Thanks! You just answered a question I’ve been beating my head against a wall for 30 minutes on.