Search Unity

Programmatically setting sprites

Discussion in '2D' started by Ozay34, Sep 22, 2017.

  1. Ozay34

    Ozay34

    Joined:
    Sep 22, 2017
    Posts:
    1
    First off, I'm pretty new to unity so I apologize if I sound like I have no clue what I'm talking about. Second, I may be asking to do something impossible. I have a script that has various options that can be set in the editor. I take those options in the Awake() method and get a sprite that I then set on the sprite renderer. Keep in mind, I also add the sprite renderer component in Awake(). This works great, however what would be ideal is having that sprite show up in the unity editor window like you added the sprite renderer component to begin with, and having the sprite actually display and be able to change the size, etc. Idealy, when you change the settings on the script, the sprite woud also change however other than that, it works exactly like the sprite renderer itself. Am I on the right track, is this even possible? Thanks for any assistance.
     
  2. FMark92

    FMark92

    Joined:
    May 18, 2017
    Posts:
    1,243
    Why are you adding another SpriteRenderer? And no, if you add another SpriteRenderer in script, you will only see it (and it's sprite) when you run the script.

    Set SpriteRendered values in update.
     
  3. Joimer

    Joimer

    Joined:
    Aug 1, 2017
    Posts:
    14
    You may add a placeholder Sprite and then programatically change the sprite:

    Code (CSharp):
    1. GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("Sprites/name");
    Remember that sprites you load through Resources.Load must be in the Resources folder.
     
  4. hlw

    hlw

    Joined:
    Aug 12, 2017
    Posts:
    250
    Everything you say is possible, it is called a Custom Editor.(Actually, FMark92 and Joimer didn't understand what you wanted) It can be a bit hard to do for a total beginner. Here is the officiel Unity tutorial to learn how to do that kind of things:

    https://unity3d.com/fr/learn/tutorials/topics/interface-essentials/building-custom-inspector

    It is a really interesting feature worth learning. This tutorial don't cover exactly what you are asking, but now you know the name of what you are looking for and basically how it works.
     
    Last edited: Sep 27, 2017