I am trying to make an if statements on characters locaation. So that if he is in a certain location something will happen to him.
However I am running into some errors.
So far what I have is this.
if (transform.position = new Vector2(-3, 0)){
transform.Translate (Vector2.right * bossSpeed * Time.deltaTime);
transform.Translate (Vector2.up * bossSpeed * Time.deltaTime);
and I keep getting errors.
I searched the forums but noone had a similar problem.
Hi NickZack,
I guess you are new to unity.
Issues in your Script:
1)Vector2.left does not exist .For this you should use (-Vector2.right).
-
In your Update function which runs continuously , you are making your object (on which script is attached) move simultaneously to left and up. Is that what you want? Because it will move out of your scene really fast.you should add controls for it like on button press or arrow keys. Or make camera follow object.
-
For comparing a condition you must use “==” & not “=”… “==” means comparing and “=” means assigning value.
-
You are using Translate and translate never reaches exact position. So the condition where you are comparing will never get executed. You should either use less than equal to 0r greater than equal to
5)Your object is never getting stopped. And you are declaring my transform variable and not using it anywhere.
I hope I am able to clarify things.
Adding a sample script . let me know if it helped you.
using UnityEngine;
using System.Collections;
public class abc : MonoBehaviour {
public float bossSpeed = 10f;
// Use this for initialization
void Start ()
{
print (transform.position);// this is the object position on which script is attached.
transform.position = new Vector3 (0, 0,0);// now we are assigning it position (0,0,0)
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.Space))// on pressing space key your object will move towards left
{
transform.Translate (-Vector3.right * bossSpeed * Time.deltaTime);
}
if (transform.position.x <= -2) //checking if object reached -2 in x direction
{
print("Reached position");
}
}
}
When you are comparing one thing to another your need to use TWO equals signs:
if (something == somethingElse)
{
DoSomething();
}
However, it VERY unlikely that a Transform’s position will equal exactly (-3, 0). You probably want to check if it is less than or equal to that value using the <= operator.
I agree with Runalotski. I would create an empty game object with a collider attached and check the “is trigger” box. I would position this where you want your player to trigger. I would then add a script to the new empty game object that follows as such:
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
DoSomething();
}
}
and then of course set the tag on your player object to “Player”.
I hope this Helps.