Accessing script on object through tag

I am using RayCast to ‘see’ an object which is then added to my ‘player’ script, it assigns a tag to the seen object, and then my player script tries to access the object’s script by finding that object through the tag, and then change a variable in a script attached to that object.

I’ve done script accessing stuff for ages, but I’m stumped with this!

theObject = GameObject.FindGameObjectWithTag("canPickUp");

theObject in my player script is accessible, but I can’t find a way of getting inside it with things like:

objectDragScript = GetComponent<ObjectDrag>();

or

theObject.ObjectDrag.playerHasSeen = true;

etc

What is the correct way of doing this? I’m sure it’s something silly I’ve missed.

I previously used collision which worked perfectly, but having two objects next to each other was a bit sketchy, so I thought raycasting was (and is) a better method.

GetComponent();
Only works if the script you are trying to fetch is on the same GameObject as the script you are in.

If you are trying to grab the script attached to a different gameobject you have to go through the reference of that gameobject.

objectDragScript = theObject.GetComponent();
objectDragScript.playerHasSeen = true;

Thanks! Yep, that’s what I have here -

theObject = GameObject.FindGameObjectWithTag("canPickUp");
objectDragScript = theObject.GetComponent<ObjectDrag>();
objectDragScript.playerHasSeenMe = true;

but I’m getting the ol;

NullReferenceException: Object reference not set to an instance of an object
PlayerController.FixedUpdate () (at Assets/scripts/PlayerController.cs:220)

As it’s not picking up the object it is touching in my GameObject theObject.
If I remove:

objectDragScript = theObject.GetComponent<ObjectDrag>();

theObject becomes the object I’m touching

This fixed it - phew!

            theObject = GameObject.FindGameObjectWithTag("canPickUp");
            if(theObject)
            {
                objectDragScript = theObject.GetComponent<ObjectDrag>();
                objectDragScript.playerHasSeenMe = true;
            }
2 Likes