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. Dismiss Notice

Is there a way to access a script by name in pragma strict

Discussion in 'Scripting' started by dansav, Mar 13, 2015.

  1. dansav

    dansav

    Joined:
    Sep 22, 2005
    Posts:
    493
    I have a game where a user can load different objects for example a catapult and a cannon.

    If a user loads an object I want to access functions in the script appropriate to that object type.

    var objectscript=GameObject.Find("catapult1").GetComponent(catapultscript);
    var objectscript=GameObject.Find("mycannon1").GetComponent(cannonscript);

    Is there a way to access the object's script using a string in pragma strict?
     
  2. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,510
    Look into the SendMessage function. If you have similarly named methods in each script, you can execute that method regardless of what type of weapon was loaded.
     
  3. dansav

    dansav

    Joined:
    Sep 22, 2005
    Posts:
    493
    Ohhh. Good idea. Thanks.
     
  4. dansav

    dansav

    Joined:
    Sep 22, 2005
    Posts:
    493
     
  5. dansav

    dansav

    Joined:
    Sep 22, 2005
    Posts:
    493
    That solved the problem of calling a function without using the name of the script, but I still need to refer to some variables in the script and access the script itself.

    Is there a way to access the object's script using a string in pragma strict?
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    If you know what the type the object is, then just store the variable as that type directly. Someone else is going to have to write the syntax out for you in JavaScript. But in C# I'm referring to this

    Code (CSharp):
    1. CatapultScript objectscript = GameObject.Find("catapult1").GetComponent<CatapultScript>();
    Alternatively you can implement an interface or use an abstract base class. But I think this is more complex then what you are asking for.
     
  7. dansav

    dansav

    Joined:
    Sep 22, 2005
    Posts:
    493
    In my situation the user can load one of many different types of machines. Each machine has a different script with its own functions and variables to set up the machine.

    Before pragma strict I used to keep an Dictionary of each object name and type and then call GetComponent(objecttype+"script") whenever I wanted the script. So I'm looking for any ideas or suggestions for accessing the scripts.