- Home /
Stop transform position moving objects together
I'm using transform position to make an object bob up and down, this works fine, however if there are two objects using the same script they move towards each other. How do I stop this?
Code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Rotator : MonoBehaviour {
private Vector3 startPos;
private Vector3 endPos;
private static Vector3 moveTo;
public static float moveSpeed = 0.005f;
private void Start()
{
startPos = this.transform.position;
endPos = this.transform.position - (new Vector3(0, 0.3f, 0));
}
// Update is called once per frame
void Update () {
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
if(transform.position == startPos)
{
moveTo = endPos;
}
if(transform.position == endPos)
{
moveTo = startPos;
}
transform.position = Vector3.MoveTowards(this.transform.position, moveTo, moveSpeed);
}
}
As a follow up, when the objects use two different scripts that are the same, they do not move together.
Answer by HammerCar · Apr 15, 2017 at 05:11 PM
I tested your code and found the problem. The moveTo variable is static. It was messing up the movement of the objects. Without the static modifier the code worked fine.
Thank you! If it's not too much to ask, what's the difference between a static and a non-static variable? Sorry I'm very new to Unity and C#.
If a variable is static the value of that variable will be same on all instances of the script.
So in your original script first the object A set the static variable moveTo to its endPos. Next the object B overwrote the moveTo variable with its own endPos. After this both of the objects were going to the same endPos.
When you used two different scripts they weren't instanses of the same script so they didn't share the same value.