0

I am trying to set different values variable for each object that I touch, and for some reason, I get that object is null - like not initialized!

The following is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class DragBall : MonoBehaviour {

    public GameObject gameObjectToDrag;

    public Text txt;

    public Vector3 GOcenter;
    public Vector3 touchPosition;
    public Vector3 offset;
    public Vector3 newGOcenter;

    RaycastHit hit;

    public int value;

    public bool draggingMode = false;

    // Use this for initialization
    void Start () {
        if (this.gameObjectToDrag != null)
        {
            if (this.gameObjectToDrag.name == "Ball1")
            {
                this.value = 1;
            }
            else if (this.gameObjectToDrag.name == "Ball2")
            {
                this.value = 2;
            }
            else if (this.gameObjectToDrag.name == "Ball3")
            {
                this.value = 3;
            }
        }
        else {
            this.txt.text = "object is null";
        }
    }

    // Update is called once per frame
    void Update () {

        if (Input.GetMouseButtonDown(0)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                this.gameObjectToDrag = hit.collider.gameObject;
                GOcenter = this.gameObjectToDrag.transform.position;
                touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                offset = touchPosition - GOcenter;
                draggingMode = true;
            }
        }

        if (Input.GetMouseButton(0)) {
            if (draggingMode) {
                touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                newGOcenter = touchPosition - offset;

                if (this.gameObjectToDrag.name == "Ball1") {
                    this.gameObjectToDrag.transform.position = new Vector3(newGOcenter.x, 1, newGOcenter.z); // 0 means Y axis , so let the ball go horizontally only
                }
                else if (this.gameObjectToDrag.name == "Ball2")
                {
                    this.gameObjectToDrag.transform.position = new Vector3(newGOcenter.x, 2, newGOcenter.z); // 0 means Y axis , so let the ball go horizontally only
                }
                else if (this.gameObjectToDrag.name == "Ball3")
                {
                    this.gameObjectToDrag.transform.position = new Vector3(newGOcenter.x, 3, newGOcenter.z); // 0 means Y axis , so let the ball go horizontally only
                }

            }
            this.txt.text = this.value + "";
        }

        if (Input.GetMouseButtonUp(0)) {
            draggingMode = false;
        }
    }
}

How do I make sure that the object is initialized and that I can set different values for each object for the public int value property?

Edit Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class DragBall : MonoBehaviour {

    public GameObject gameObjectToDrag;

    public Text txt;

    private int value;

    public Vector3 GOcenter;
    public Vector3 touchPosition;
    public Vector3 offset;
    public Vector3 newGOcenter;

    RaycastHit hit;

    public bool draggingMode = false;

    // Use this for initialization
    void Start () {
        if (this.gameObject.name == "Ball1")
        {
            this.value = 1;
            Debug.Log("BALL 1 VALUE SET TO " + value);
        }
        else if (this.gameObject.name == "Ball2")
        {
            this.value = 2;
            Debug.Log("BALL 2 VALUE SET TO " + value);
        }
        else if (this.gameObject.name == "Ball3")
        {
            this.value = 3;
            Debug.Log("BALL 3 VALUE SET TO " + value);
        }
    }

    // Update is called once per frame
    void Update () {

        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("Mouse is pressed down");
            Camera cam = Camera.main;

            //Raycast depends on camera projection mode
            Vector2 origin = Vector2.zero;
            Vector2 dir = Vector2.zero;

            if (cam.orthographic)
            {
                origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            }
            else
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                origin = ray.origin;
                dir = ray.direction;
            }

            RaycastHit2D hit = Physics2D.Raycast(origin, dir);

            //Check if we hit anything
            if (hit)
            {
                Debug.Log("We hit " + hit.collider.name);

                this.gameObjectToDrag = hit.collider.gameObject;
                GOcenter = this.gameObjectToDrag.transform.position;
                touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                offset = touchPosition - GOcenter;
                draggingMode = true;
            }
        }

        if (Input.GetMouseButton(0))
        {
            if (draggingMode)
            {
                touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                newGOcenter = touchPosition - offset;

                if (this.gameObjectToDrag.name == "Ball1")
                {
                    this.gameObjectToDrag.transform.position = new Vector3(newGOcenter.x, 1, newGOcenter.z); // 0 means Y axis , so let the ball go horizontally only
                }
                else if (this.gameObjectToDrag.name == "Ball2")
                {
                    this.gameObjectToDrag.transform.position = new Vector3(newGOcenter.x, 2, newGOcenter.z); // 0 means Y axis , so let the ball go horizontally only
                }
                else if (this.gameObjectToDrag.name == "Ball3")
                {
                    this.gameObjectToDrag.transform.position = new Vector3(newGOcenter.x, 3, newGOcenter.z); // 0 means Y axis , so let the ball go horizontally only
                }

            }
        }

        if (Input.GetMouseButtonUp(0))
        {
            draggingMode = false;
        }

    }
}
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Mizlul
  • 1
  • 7
  • 41
  • 100
  • What object are we talking about here? What line or area specifically is causing the problems? – Ryanas Mar 29 '18 at 21:14
  • this line is causing the problem if I remove the outer condition and leave as if (this.gameObjectToDrag.name == "Ball1"), basically this.gameObjectToDrag is null and I am trying to access a property name of it, for some reason if I move this line of code within update inside if conditions it works – Mizlul Mar 29 '18 at 21:16
  • In my other answer, I used `this.gameObject.name` in the `Start` function. Why did you change it to `this.gameObjectToDrag.name`? – Programmer Mar 29 '18 at 22:03
  • @Programmer I changed thout I should use the reference I Defined as GameObject, but eventhou now I changed to this.gameObject.name, looks like the objects still havent got their value property initiated by using if (this.gameObject.name == "Ball1") { this.value = 1; } – Mizlul Mar 29 '18 at 22:17
  • I have this now: void Start () { if (this.gameObject.name == "Ball1") { this.value = 1; Debug.Log("BALL 1 VALUE SET TO " + this.value); } else if (this.gameObject.name == "Ball2") { this.value = 2; Debug.Log("BALL 1 VALUE SET TO " + this.value); } else if (this.gameObject.name == "Ball3") { this.value = 3; Debug.Log("BALL 1 VALUE SET TO " + this.value); } } – Mizlul Mar 29 '18 at 22:24
  • Edit your question with the proper code. At the end of it, add `Debug.Log(value)`. Check the Console tab and tell me the output. Should be 1, 2 and 3 from each script instance. Again I need to see the edit to make sure you are not doing something else. Don't forget the `Debug.Log(value)` – Programmer Mar 29 '18 at 22:33
  • updated question, https://ibb.co/gaNjen check the console @Programmer – Mizlul Mar 29 '18 at 22:39
  • but still the text does not display correct value when touching the object, keep showing 2 I dont know eventhou I try to touch all of them but it does not change – Mizlul Mar 29 '18 at 22:41
  • 1
    Ok, that part is fixed. It now shows that they are all receiving different values. Don't change it again as you are making it more complicated to help you.Now, please describe what you are trying to do. I think that will be easier to understand than your current question. You want to detect when each object is clicked then print out that `value` variable? – Programmer Mar 29 '18 at 22:44
  • @Programmer exactly, I wanna see when I touch an object, show it's value propery, display in text! – Mizlul Mar 29 '18 at 22:49
  • so many things you did wrong. **1.** You are using `SpriteRenderer` which makes it a 2D image. To detect clicks on 2D/SpriteRenderer image, you have to use `Collider2D` not `Collider`. Instead of using `BoxCollider`, that should be `BoxCollider2D`. **2.** To detect the click on 2D/SpriteRenderer , `Physics2D.Raycast` should be used not the `Physics.Raycast` in your question. `Physics.Raycast` and `BoxCollider` are for 3D objects like `MeshRenderer`. – Programmer Mar 29 '18 at 22:55
  • ok will try to change the code as per ur suggestions! – Mizlul Mar 29 '18 at 22:59
  • By the way, stay away from raycast for this. Don't use `Physics2D.Raycast` to detect clicks. It works but there is a better and new way to do it. Use the event system. See **#7** from [this](https://stackoverflow.com/questions/41391708/how-to-detect-click-touch-events-on-ui-and-gameobjects) post. It shows how to detect click on 2D object. Make sure to fix the collider problem I described. If there is a detection problem let me know but make sure to read that post first to save our time. Always use `Debug.Log` to see what's not working and always edit and add your new code – Programmer Mar 29 '18 at 22:59
  • @Programmer, since this is also my learning curve, can I stick at this moment with Physics2D.Raycast so that I dont have to change alot in my code, I just want to make it work as a prototype first! Now that I changed to BoxCollider2D and updated the code my objets does not move at all, could u provide me a sample of code for Raycast2D? – Mizlul Mar 29 '18 at 23:07
  • @Mizlul The event system I recommded is better because it has `OnBeginDrag`, `OnDrag` and `OnEndDrag` which you need and works on both mobile and desktop. It's better to do it the correct way now than to have to re-write the code later on. Anyways, check [this](https://stackoverflow.com/questions/30291233/onmousedown-on-box-collider-2d-not-firing/30292549#30292549) post. It has function with example on how to do that and you must call that function from the `Update` function to make it run every frame. – Programmer Mar 29 '18 at 23:49
  • @Programmer thnx for the help, I made so the object are now moving on click using the RaycastHit2D, the only thing missing is I want to print out the value based on what was hit. I am debuging Debug.Log(this.value) it always returns 2, idk why! Althou we have different value for each instance, so normally should value should display based on what was clicked/hit – Mizlul Mar 30 '18 at 00:11
  • Add your new code to your question. It is fine to just modify the last code in your question instead of adding new one that makes it 3 code – Programmer Mar 30 '18 at 00:12
  • updated, u can check! – Mizlul Mar 30 '18 at 00:14
  • @Programmer, what I mean is smth like, now that I am hitting Ball3, give me his value property so basically it should give 3 and display it on Text Label... I guess I dont have value property separate for each object that I can access smth like GameObject.Find("Ball3").value smth like this – Mizlul Mar 30 '18 at 00:20
  • You need to put `Debug.Log(value)` inside `hit` to make sure it's working or not . You have not done this and I've been saying this for so long. Use `Debug.Log(value)`. – Programmer Mar 30 '18 at 00:22
  • I have added already and told u that it always prints 2 on the log, sorry I may not have it on the latest update, but yeah I tried that, still not able to get the correct value depending on which object I am dragging! – Mizlul Mar 30 '18 at 00:27
  • seems like what I am trying to achieve is not possible as it seems that I only have one copy of value property for all instances and I am updating it based on what I am dragging, Idk if there is a way that I can have value property for each object separately! – Mizlul Mar 30 '18 at 00:29
  • smth like, Ball1.value = 1, Ball2.value = 2, Ball3.value = 3 – Mizlul Mar 30 '18 at 00:31
  • I may create a key value pair list and store each object and its value, and later when I need value for each object I may lookup by its name give the corrosponding value! – Mizlul Mar 30 '18 at 00:34
  • I think you have already helped me quite alot, I really appreciate the time you gave it, looks like I need to read more the Unity Documentation! – Mizlul Mar 30 '18 at 00:36

0 Answers0