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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Is it possible to access or load an Asset at runtime?

Discussion in 'Scripting' started by GrayDwarf, Nov 27, 2019.

  1. GrayDwarf

    GrayDwarf

    Joined:
    May 6, 2015
    Posts:
    9
    I've got a basic state machine for a text adventure and I'm trying to figure out how I can jump to any state from within the game script.

    Something like this where I can get the state and then work with it.
    Code (CSharp):
    1.  
    2. State jumpToState = Resources.Load("11") as State;
    3. textComponent.text = state.GetStateStory();
    4.  
    I've got a state named "11" in my Assets folder and it's of type ScriptableObject.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    It has to be in a folder called Resources (obviously also under Assets somehwere) and then the above should work.

    However, please use this format of the line 2 above:

    Code (csharp):
    1. State jumpToState = Resources.Load<State>( "11");
    because it will guard against Unity asset ordering inconsistencies that might trip you up, i.e, if you have a texture or material in that same directory called 11.png or 11.mat, the way it was originally written may return the wrong object.
     
    GrayDwarf likes this.
  3. GrayDwarf

    GrayDwarf

    Joined:
    May 6, 2015
    Posts:
    9
    That worked. Thanks!
     
    Kurt-Dekker likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    BTW, hearing of you making a text adventure in Unity3D here in 2019 really made me smile. I grew up with all the Infocom early stuff, so I just wanna say, "Cool!"

    In other news, you oughta post a link here on the forums (there's a show-off group separate from this group) when you get your first playable going!