How To Call A Static Script With A Variable String

I have a variable string that I would like to pass into a call to a static script:

I have many different characters, each with a static script:

public class SA_Character_MaleSurvivor02 : MonoBehaviour {
    //*********************************************
    // Static pointer to this script
    public static SA_Character_MaleSurvivor02 Current;
    public SA_Character_MaleSurvivor02(){
        Current = this;
    }
    //*********************************************

        public GameObject selectionPlane;

        public void TurnOnSelectionPlane(){
        selectionPlane.SetActive (true);
    }

In my SelectionManager, I am using a Raycast to return the name of the object that corresponds to their static script. Once I have the name, how to I go about passing that along? This doesn’t work:

if(Input.GetMouseButtonDown(0)){
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit, Mathf.Infinity)){
                if (hit.transform.root.tag == "Human") {
                    selected = true;
                    selectedName = hit.transform.root.name;
                    selectedName.Current.TurnOnSelectionPlane ();
                }
            }
        }

So the issue is, when passing in selectedName (which is the correct name [as a string] I’m trying to use) to the static Current.TurnOnSelection, there is no reference… which I’d expect. But I’m not sure how to make it work…

Thanks, everyone!

I wouldn’t make it static myself and I wouldn’t have a different script for each character. I would have a single Character script and look for that.

Thanks for the reply!

Each character is unique, and so I decided to try an approach where they each have a static “card” with the same name as the name of the model in the scene. I theory, I should be able to return the name of the model from a Raycast and use that to call its static script.

While I can appreciate your idea, that doesn’t help with trying to pass in a string here. In web development I’ve had to prepare strings with variables to then call… is there a way to prepare this line and then use it?

string x = selectedName + ".Current.TurnOnSelectionPlane();";

Your SA_Character_MaleSurvivor02 follows a similar idea as a singleton.(it’s not exactly one, but close.)

So you need to access the current variable through the class itself instead of an instance of the class.

SA_Character_MaleSurvivor02.Current.DoSomethingWithAString(“thisisastring”);

Yes, Singleton ideas are where I brainstormed up this idea.

The models in the scene and their static classes have the same names (in this case “SA_Character_MaleSurvivor02” for the model and the static class), and the idea is to use a Raycast, find the name of the model hit (since I’m using Ragdoll Rigidbodies and not a BoxCollider attached to the character, I have to find the root name, since the hit returns the bodypart hit) and then pass that string name to call the class of that model.

Forgot to refresh the page before responding.

TurnOnSelectionPlane doesn’t take a string parameter?

Maybe I’m missing something, but if you hit a human tag, and want to access a method on a static instance, you’d do:
SA_Character_MaleSurvivor2.Current.TurnOnSelectionPlane(stringVar);

Maybe you want:
SA_Character_MaleSurvivor2.Current = hit.GetComponent<SA_Character_MaleSurvivor2>();

Yes, there are quite a few different characters in the scene, each with a different static script (named the same as the character in the scene). I am using the “Human” tag to return the human characters from the Raycast, and then use the hit.transform.root.name to populate which script needs to be called.

The GetComponent was a good idea, but I’d still have to be able to pass in a to find the right script. As is, it looks like having the method I’m trying to call in the static class may not be feasible. I should be able to find the GameObject I’m trying to access from the hit.

If you made it just a public void method then you could do this;

        var myObject = hit.gameObject.GetComponent(hit.transform.root.name);
        myObject.SendMessage("TurnOnSelectionPlane ");

Although I hate to recommend finding things via strings. I still think you would be better off have a universal character script which can be tailored for each type.

the class you wrote out in your post isn’t static, to begin with. I’m just a little confused.
Anyways, based on the update you gave, @WarmedxMints_1 answer is good.
You could also use an interface, if not a universal script, and fetch the interface instead of the name.
As is often the case with programming, many options are available. Hopefully one suits ya :slight_smile:

You’re probably right about that.

I say static because I don’t know the right term for it. I got around it by just making the SelectionManager “static”, setting a bool on the Raycast hit, and then just checking for that bool back on the character’s script.

SelectionManager.cs

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

public class SelectionManager : MonoBehaviour {

    //*********************************************
    // Static pointer to this script
    public static SelectionManager Current;
    public SelectionManager(){
        Current = this;
    }
    //*********************************************

    public bool selected = false;
    public string selectedName;

    public SelectionInteraction selectionPlane;

    void Start(){
       
    }

    void Update(){
        if(Input.GetMouseButtonDown(0)){
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit, Mathf.Infinity)){
                if (hit.transform.root.tag == "Human") {
                    selected = true;
                } else {
                    selected = false;
                }
            }
        }
    }
}

Character script:

void Update(){
        if(currentHealth <= 0 && isDead == false){
            Die ();
        }

        if(SelectionManager.Current.selected == true){
            TurnOnSelectionPlane ();
        }

        if(SelectionManager.Current.selected == false){
            TurnOffSelectionPlane ();
        }
    }

        public void TurnOnSelectionPlane(){
        selectionPlane.SetActive (true);
    }

    public void TurnOffSelectionPlane(){
        selectionPlane.SetActive (false);
    }

If all the characters are reading that bool in their update, then they would all b e set active.

First of all, use Awake instead of the constructor in MonoBehaviours.
You almost never want to use a MonoBehaviour’s constructor.

Secondly, the advice about having a class for the characters or at least parts of it is probably what you’re looking for. Not a class for every character.
The diversity can be modelled with inheritance, interfaces, additional components for specialization (composition) and other OOP techniques.

C# is a strongly typed language, make use of that and avoid relying on these string-based approaches.

1 Like

For starters, thanks for the replies!

I agree, that worked fine for one model in the scene, but not for multiples reading the bool, I’ll have to add to that.

I can appreciate the thumbs up on the single class, and maybe I’ll go back to that. I am trying to brainstorm avenues that make sense to me to make a complex game, and the single class for each character is not without its own complications and complexity.

Do you know if there is a way to make this call with a variable?

Several options exist

The best would be to use the same class for each survivor.

The second best would be to use a common abstract base class or a common interface.

But if you really want to persist in using strings, there is a technique called reflection. Reflection lets you read the metadata about your code at runtime. It also lets you do things like generate references from strings. But be warned, Reflection is a deep rabbit hole. You probably don’t want to go down it.

1 Like

That’s because of the way you work with statics.
Statics can be very useful (and they’re indeed), but only if they’re used appropriately.

Often, they’re misused for convenience: passing around data, having a “global” and single point of access. Some patterns actually encourage you to do this in some way, but then there’s usually more to it than just convenient access (e.g. singletons).

So in your case for example, the selection manager could be a singleton, it doesn’t have to be one though.
For your scenario, you’ll most-likely only ever need/want a single selection manager, a second one would be redundant, useless and might cause weird bugs.

There’re many other approaches to ensure singleton behaviour without having the singleton implementation directly in your classes. But that’s a huge topic for itself.

So all you might need at the moment is the SelectionManager, an interface (what about ISelectable?) and your character information (maybe Character[Description]?).
You can invest more time to build up an even better structure, but that should be sufficient for now, evne though “ISelectable” is a quite generic/abstract term.

Anyway, the selection manager does its thing: it figures out what you’ve been clicked on. That’s all.

In the most abstract approach, the SelectionManager doesn’t even need to know what exactly has been clicked, but only that some selectable thing has been clicked
So it would only ever track the current “ISelectable” and call “Select” and “Deselect” (or “OnSelected” and “OnDeselected” respectively) on it.

What happens then is not his concern, it’s up to the actual selected item. Maybe it spins, maybe it deletes itself, maybe it changes colors.

A good alternative, which does not only save you alot of time but is way more reliable, is Unity’s event system. It offers a variety of different interfaces that you only need to implement. The system additionally plays nicely with UI so that it blocks clicks when its in front of your clickable objects.
Your current approach does not take these things into account and this is usually a bad user experience.

Well yes, you only need a method with parameters, so that you can pass actual arguments into it.

1 Like

Thanks for the great reply! I’m sorry, it’s 11:09 and I can’t possibly do your post justice!

This has worked pretty well:

SelectionManager.cs

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

public class SelectionManager : MonoBehaviour {

    //*********************************************
    // Static pointer to this script
    public static SelectionManager Current;
    public SelectionManager(){
        Current = this;
    }
    //*********************************************

    public bool selected = false;

    public string selectionName = " ";

    public SelectionInteraction selectionPlane = null;

    void Start(){
       
    }

    void Update(){
        if(Input.GetMouseButtonDown(0)){
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            if (Physics.Raycast (ray, out hit, Mathf.Infinity)){
                if (hit.transform.root.tag == "Human" && selectionPlane != null) {
                    selectionPlane.selectionPlaneReference.SetActive (false);
                    selectionPlane = null;
                    selectionName = " ";
                    selected = false;
                }

                if(hit.transform.root.tag == "Human" && selectionPlane == null){
                    selected = true;
                    selectionName = hit.transform.root.name;
                    selectionPlane = hit.transform.root.GetComponent<SelectionInteraction>();
                    selectionPlane.selectionPlaneReference.SetActive (true);
                } else {
                    if (selectionPlane != null) {
                        selectionPlane.selectionPlaneReference.SetActive (false);
                        selectionPlane = null;
                        selectionName =  " ";
                        selected = false;
                    }
                }
            }
        }
    }
}

… and then SelectionInteraction.cs on each object:

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

public class SelectionInteraction : MonoBehaviour {

    public GameObject selectionPlaneReference;

}

Seems to work pretty good so far… even if it’s pretty much the opposite of what you said I should be doing… sorry =)

The hit is doing pretty much all the work in the Raycast!

Thanks much for helping me work through these ideas! Fortunately it’s modular enough that if (when?) this “static” card idea fails I can go back to

Thanks for the advice, fortunately I’ve kept it modular to avoid that complication, and there’s been enough to ditch the idea already.

Thanks! It’s already been enough of a pain to ditch the idea altogether, and thanks for pointing me in good directions!