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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How can I change layer of an object that isn't there before the game is started?

Discussion in 'Scripting' started by Temp10101, Apr 16, 2015.

  1. Temp10101

    Temp10101

    Joined:
    Feb 11, 2015
    Posts:
    54
    Sorry for throwing this question just like that upon you, project has to be done in 3 hours and I still have a lot to do.

    I have made a script which randomly places "Coins(Clone)" on map about 25 times, but I need to change it's layer of order to 1. Worth noting that these instances are made out of prefab and don't exist before the game is started.

    How can I do that? Sorry for throwing this question once again, I could make invesitgation but, there's still lot to do.
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    when you instantiate, set the layer of the gameobject.

    Code (csharp):
    1.  
    2. var coin = Object.Instantiate(coinPrefab) as GameObject;
    3. coin.layer = 1;
    4.  
    I'm assuming you mean the layer property on the GameObject used for Physics and Camera rendering... if you're talking about some other layer, you'll need to define what layer you're talking about.
     
    Temp10101 likes this.
  3. Temp10101

    Temp10101

    Joined:
    Feb 11, 2015
    Posts:
    54
    I meant "Sprite Renderer > Order in Layer" :)
    But thank you for your very fast response and help. (still need the working one though :p )
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    Is the SpriteRenderer on the root of the prefab?

    If so, get the SpriterRenderer off of it and set the 'sortingOrder' (that's the actual property you're looking for).

    Code (csharp):
    1.  
    2. var coin = Object.Instantiate(coinPrefab) as GameObject;
    3. var renderer = coin.GetComponent<SpriteRenderer>(); //if it's on a child, you'll need to find the child first
    4. renderer.sortingOrder = 1;
    5.  
    Is there a reason the prefab can't have it set to 1 in the first place???
     
    Temp10101 likes this.
  5. Temp10101

    Temp10101

    Joined:
    Feb 11, 2015
    Posts:
    54
    Is the SpriteRenderer on the root of the prefab?

    (facepalm) I'm an idiot... I could've just set Prefab to Layer 1... and copies will inherit it... oh man... sorry for wasting your time. Thank you for your responses.