Calling function from a script to another script only working on one game object

I have 2 gameobects representing buildings. each of those has a 2D Box Collider attached, and a script I made called “SelectableObject”. The SelectableObject script has a function in it called “SelectObject(Bool selected)”
I want to call this function on the object that is touched by the user (detected via raycaster with the box collider).

My SelectableObject code is as follows

public class SelectableObject : MonoBehaviour {
    // If this item is selected, can't be static.
    private bool isSelected=false;
    // A reference to the line renderer.
    private GameObject lineRendererObject;

    // The points of the line, these can be static because only one object is ever selected.
    // Don't want to create a copy for each object;
    static float leftX;
    static float rightX;
    static float topY;
    static float bottomY;
    private UnityEngine.UI.Text myText;

    // Use this for initialization
    void Start()
    {
        lineRendererObject = GameObject.Find("BoxingRendererObject");
        lineRendererObject.SetActive(false);
        myText = GameObject.Find("DebugText").GetComponent<Text>();
    }

    public void selectObject(bool selected)
    {
        myText.text = "Inside the selectedObject The game object is " + gameObject + " the next selected object is " +this;

        isSelected = selected;
    }

}

My code that calls the “selectObject” function lives in my EventSystem object and is as follows:

    // stores the currently selected object
    private SelectableObject selectedObject;
    // stores the object to be selected next
    private SelectableObject nextSelectedObject;
    // Last touch
    private Touch lastTouch;
    // Update is called once per frame

    void Update()
    {
        if (Input.touches.Length > 0)
        {
            // Just care about the most recent touch
            lastTouch = Input.touches[Input.touches.Length - 1];


            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(lastTouch.position), Vector2.zero);

            // make sure we did hit soomething, and it did collide with something
            if (hit != null && hit.collider != null)
            {
                nextSelectedObject = hit.collider.gameObject.GetComponent<SelectableObject>();
                    //        myText.text = hit.collider.name;
                // If the newly selected object does not equal null.
                if ( nextSelectedObject != null )
                {
                   
                    // if the previous select object was not null and isn't the same as our new object
                    if (selectedObject != null && selectedObject != nextSelectedObject)
                    {
                        // set the old object to not selected.
                        selectedObject.selectObject(false);
                    }

                    // set our reference to the new object
                    selectedObject = nextSelectedObject;
                    // set the new object to selected

                    selectedObject.selectObject(true);
            
                }
            }
            else
            {
                if (selectedObject != null)
                {
                    selectedObject.selectObject(false);
                    selectedObject = null;
                }
            }

        }

    }

The problem is this, this only works on one object, what I mean is, the selectObject function only ever gets called for one of the 2 selectable objects. (Note if I remove the selectableObject script from the gameObject then the other gameobject also works fine!
Also note that I have printed out the gameObject name and the script name right before selectedObject.selectObject(true); and everything seems ok in both cases… but for some reason the function call just isn’t getting there! I am going crazy here.

lineRendererObject = GameObject.Find(“BoxingRendererObject”);

Do you have more than one BoxingRendererObject in the scene?

No, just one. That is used to draw a box around the object that is selected (and it does work for the one object that is getting the call through to “selectObject(bool)” and when I click off that object the box goes away as it should.

I have put an output statement at line 38 of the second code snippet, the line is as follows

          myText.text = "The game object is " + hit.collider.gameObject + " the next selected object is " + selectedObject.ToString();

myText is a reference to a text box for display. When I click on either of the gameObjects I see the correct information displayed, the gameObject name matches the one clicked, and the selected object shows it is a selectableObject… but yet the function call right after that never works for one of the game objects.

Sorry, I’m not sure what you are saying or what the expected output is. You are clicking on an object and after hitting it, you call the selectObject on it. However, you are turning off the previous object if you already have something selected.

So, this call here
myText.text = "Inside the selectedObject The game object is " + gameObject + " the next selected object is " +this;

It’s not giving you the result you expect? Both gameObject and this will basically return the same object (one is the gameobject, one is the script attached to the gameObject)

What function call isn’t working?

the call on line 39, selectedObject.selectObect(true); will only ever go to one of the selectableObject.

I think using my game code may have overs complicated things. Try this instead, if I do the following

                 GameObject.Find("CratePinkGridSprite").GetComponent<SelectableObject>().selectObject(true);
                GameObject.Find("TownCenter").GetComponent<SelectableObject>().selectObject(true);

and both of those game objects have the SelectableObject script attached to them (Via the inspector), the call to SelectObject(true); on the TownCenter never works… however if I remove the script from the CratePinkGridSprite (and take out the call to SelectOBject(true) on that gameobject), then the call on the town center object works. It is as if the script cant be attached to two things at once! but it should be able to since each gameobject should get its own instance of the component, right?

So, within the selectObject method, if you put in a debug.Log(gameObject.name) it always prints out CratePinkGridSprite?

Even if you call it on the townCenter. Or the TownCenter never gets called (using the two lines you posted above)

Yes exactly right it only prints out the one, and even with the two lines above it never gets called on the TownCenter…

Even if I leave just this line
GameObject.Find(“TownCenter”).GetComponent().selectObject(true);
and remove the other one, it still won’t work. but If I unattach the SelectableObject from the other gameobjet (CratePinkGridSprite) then that call will work.

I even tried creating another script called “SelectableObj” with the exact same code as “SelectableObject” and tried using different calls like so:

GameObject.Find("CratePinkGridSprite").GetComponent<SelectableObj>().selectObject(true);
                GameObject.Find("TownCenter").GetComponent<SelectableObject>().selectObject(true);

and it still would not work! I had to delete the “SeletableObj” script off of the CratePinkGrideSprite before the call would work on the TownCenter object…

At this point I am so desperate I am trying to reinstall unity. I am a professional developer and this is just not making any logical sense (my debugger also wont work, it hasn’t since I installed, so my guess is something with this version/install didn’t go well)… keep fingers crossed.

Didn’t you mean to use a 3D Raycast with a forward direction instead? A direction of zero would never hit anything afaik.

The game is 2D so it does hit the objects. (that part actually works perfect, I can actually add a box collider to several objects and see that each of them can be hit by touching the screen).

The problem comes when trying to call the function that is in the SelectableObject script attached to each object. That call will only ever go to one of the objects, to all others it fails.

I have figured out that the script is not being attached to the other objects, it is only being attached to the one object. The inspector shows that I have attached it to all three. I came to this conclusion because I put this code in the LateUpdate call of the script.

    if (gameObject == GameObject.Find("CratePinkGridSprite"))
        { }
        else
        {
            myText.text = "testing  " + gameObject + isSelected;
        }

and nothing appears in my text box. But if I take out the if statement and just do the print it will print the CratePinkGridSprite object.

Any ideas why this script would not accept being attached to multiple different sprites?

Honestly, at this point, I’m not sure what is going on without seeing the project. I’ve never encountered an issue if I add a script to a gameobject in the scene that it wouldn’t be there when I run the game.

These are scripts added to the objects in the scene and not on prefabs, right?

I’m fairly certain that Physics2D.Raycast will not collide with a BoxCollider.
I’d suggest not having “nextSelectedObject” as a member variables, it makes it usage more clear and ensures you aren’t messing with left over hits from the previous frame.
Also, comparing hit to null will always result in true. “hit” cannot be null as it is a struct.
As @Pengocat mentioned, a direction of zero will not hit anything.

I can’t see how your Raycast is colliding with anything. I’d suggest rendering it in the scene view using Debug.DrawRay or Debug.DrawLine.

Solved it!
Installing a different version of Unity got my debug, specifically the console, up and working. That allowed me to see that a null was being referenced somewhere, and that was in these lines of SelectableObject:

        lineRendererObject = GameObject.Find("BoxingRendererObject");
        lineRendererObject.SetActive(false);

That was in the start called, so apparently when the next object when to get the “BoxingRendererObject” it could not find it since it had been deactivated, so only the first object (in this case the pink crate object) got a copy of it! Oddly the objects that had the null reference were still drawn, but anything in that script with the null reference would not work.

The Physics2D.Raycast is colliding with a 2DBoxCollider << I would imagine because z is ignored in 2D space?

Thank you for the point on hit being a struct and not being null, I will clean that up.

I did not know you could drawray! that is sweet, I will give that a shot to see what that looks like.

Thank you guys so much for your help!! Turns out getting the debugger to actually work makes life a lot easier. Still not sure why it wasn’t working!