Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Resolved private static changes for all generated objects anyway.

Discussion in 'Scripting' started by JeaNiX, Jan 31, 2021.

  1. JeaNiX

    JeaNiX

    Joined:
    Oct 31, 2016
    Posts:
    20
    Hello there,
    I'm trying to generate some objects, and there is a object that should move on the the Y axis, while colliding with the upper or lower object it should change from y = -y etc. It's working as it should, but if another object generates that can move on a lower distance, the first object will also change movement direction with the second object. All objects change directions together. Killed the day making this whole logic without colliders, had other problems. Now trying with them and run in this problem. Any way to fix it? Thanks!
    private static float speed = 2.0f;
    private static Vector3 moveVector = new Vector3(0, 1, 0);
    void Start()
    {
    }
    private void OnTriggerEnter(Collider other)
    {
    moveVector = moveVector * -1;
    }
    private void Update()
    {
    gameObject.transform.Translate(moveVector * speed * Time.deltaTime);
    }
     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    That's the intended purpose of the
    static
    keyword. It creates one instance of something shared across the entire application. Changing a
    static
    variable affects everything that reads from it.

    In a nutshell, here's a diagram of how it works. Each object instance shares the value of moveVector because it's static:
    upload_2021-1-31_11-54-47.png
    If you don't make moveVector static, then it is relative to each object instance, and changing it will only affect the object that it was changed on:
    upload_2021-1-31_11-56-16.png


    I don't see why you need to make these fields in your class static anyway, so why not just remove the
    static
    keyword?
     
    eisenpony likes this.
  3. JeaNiX

    JeaNiX

    Joined:
    Oct 31, 2016
    Posts:
    20
    Thank you very much.
    While doing the prototype project from the tutorials here I needed to make a variable static, so it don't change. That's why I made it here the same, but this is a different situation. I understand it now. Thank you for the tip and for the diagram, now it's working perfectly! ^_^
     
    Vryken likes this.