• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by lukazkool · May 15 at 07:28 PM · prefabvariablelocal

How to make variables local to one instance of a prefab?

My question is pretty straightforward, I am trying to find a way to create local variables that only apply to the instance of the prefab they are attached to, yet I cannot wrap my head around on how to fix it.

Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image

Answer by unity_6255F9AC6E8A43BB555E · May 15 at 10:47 PM

All variables only "apply" to a specific instance of a prefab unless they're static. Are you making public variables and then altering them in the inspector? If so, the values in the inspector will be used regardless of any default values assigned to them in the script. However, they will still be able to be altered independently when the prefab is instantiated.

Also, make sure you are altering the the instantiated objects in the hierarchy (and not the prefab asset itself in the project tab) if you are trying to adjust the values independently during runtime. Instantiated prefabs will be marked by (Clone) after their name in the hierarchy.

If you instantiated a prefab by dragging it into the scene in edit mode, it won't have (Clone) in its name, but it will have a different icon with blue text. Just like with the clones, you can adjust their public variables in the inspector independently of the parent prefab asset. These will also have an "overrides" option at the top of the inspector which will allow you to revert back to the original prefab, or apply the changes of the instance back to the original prefab.

Comment

People who like this

0 Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image lukazkool · 3 days ago 0
Share

What I am doing is assigning a variable through script, [System.NonSerialized] int tileLevel = 0; but when I go to change it through script, it changes publicly through all instances of the prefab and not just the one I wanted to.

avatar image

Answer by zereda-games · 3 days ago

would help seeing some of the code you are using to bring the prefab into the scene.

Best practice

 using UnityEngine.UI;
 public class MyPrefabClass : MonoBehaviour
 {
     public Text textObj = null;
     [System.NonSerialized] int tileLevel = 0;
     public int GetTileLevel { get { return tileLevel; } }
     public int SetTileLevel { set { tileLevel = value; } }
 }
  
 using System.Collections.Generic;
 public class MyControlClass : MonoBehaviour
 {
     public int prefabPadding = 25;//Set to ur prefabs height
     public string prefabName = "Prefab";
     public string resources = "Prefabs/";
     public string resourcesActualLocation = "Assets/Resources/Prefabs/";
     public GameObject scrollViewContent;//Probably a vertical scroll view set up on this GameObject to create a list.
     static GameObject prefab = null;
     [SerializeField] List<GameObject> prefabsList = new List<GameObject>();
 
     public int GetTileLevel(int index)
     {
         //Set a default to return.
         int tileLevel = 0;
         //Make sure list isn't null or has a count
         if (prefabsList != null && prefabsList.Count >= 1)
             //Loop though whole List
             for (int i = 0; i < prefabsList.Count; i++)
                 //Find Spacific Index
                 if (index == i)
                 {
                     tileLevel = prefabsList[i].GetComponent<MyPrefabClass>().GetTileLevel;
                     prefabsList[i].GetComponent<MyPrefabClass>().textObj.text = tileLevel.ToString();
                 }
         return tileLevel;
     }
     public void SetTileLevel(int index, int newTileLevelValue)
     {
         //Make sure list isn't null or has a count
         if (prefabsList != null && prefabsList.Count >= 1)
             //Loop though whole List
             for (int i = 0; i < prefabsList.Count; i++)
                 //Find Spacific Index
                 if (index == i)
                 {
                     prefabsList[i].GetComponent<MyPrefabClass>().SetTileLevel = newTileLevelValue;
                     prefabsList[i].GetComponent<MyPrefabClass>().textObj.text = GetTileLevel(i).ToString();
                 }
     }
 
     /// <summary>
     /// Makes a new Game Object and instantiates it.
     /// </summary>
     public void CreateNewPrefabScenePrefabOnList(string objectName)
     {
         if (prefab == null)
             prefab = GetPrefabPanel;
 
         //Create a new prefab in scene on the list object
         GameObject obj = Instantiate(prefab, scrollViewContent.transform);
         CreateNewPrefabScenePrefabOnList(objectName, obj, prefabPadding);
     }
     public void AddPrefab(GameObject prefabCopy, int newTileLevelValue = 0)
     {
         if (prefabsList == null)
             prefabsList = new List<GameObject>();
         prefabsList.Add(prefabCopy);
         SetTileLevel(prefabsList.Count, newTileLevelValue);
     }
     public void RemovePrefabFromList(int Index, bool destroy = false)
     {
         //If list doesn't exists stop
         if (prefabsList == null)
             return;
 
         //Make empty GO in case we Find the object we can cache it.
         GameObject temp = null;
 
         //Loop list to find object and set it
         for (int i = 0; i < prefabsList.Count; i++)
             if (i == Index)
                 temp = prefabsList[i];
 
         //Remove from list
         prefabsList.RemoveAt(Index);
 
         //And lastly destroy if destroy = true.
         if (destroy)
             Destroy(temp);
     }
     public void RemoveAllObjectFromSceneByTag(string tag)
     {
         //Find all prefabs in scene and collect them in a list.
         //   then Destroy each object in the list.
         GameObject[] prefabs = GameObject.FindGameObjectsWithTag(tag);
         foreach (GameObject go in prefabs)
             Destroy(go);
     }
     public void RemoveAllPrefabsFromSceneFromSavedList()
     {
         foreach (GameObject go in prefabsList)
             Destroy(go);
     }
 
     /// <summary>
     /// Loads a prefab from resources.
     /// </summary>
     GameObject GetPrefabPanel
     {
         get
         {
             if (prefab == null)
             {
                 prefab = Resources.Load<GameObject>(resources + prefabName);
 #if UNITY_EDITOR
                 if (prefab != null)
                     Debug.Log(string.Format("{2} found in {1}. [{0}]", prefab, resourcesActualLocation, "Panel Prefab"));
                 else
                     Debug.LogError(string.Format("{2} was not found in {1}.", prefab, resourcesActualLocation));
 #endif
             }
             return prefab;
         }
     }
     void CreateNewPrefabScenePrefabOnList(string objectName, GameObject panel, int contentPadding, int tileLevelValue = 0)
     {
         //Increase the size of the scroll view area by the hight of the prefab [Set in inspector]
         IncreaseScrollViewWindowSize(panel, contentPadding);
 
         //Rename this object for easy finding later.
         panel.name = string.Format("{0}{1}", objectName, prefabsList.Count + 1);
 
         //Add and set value
         AddPrefab(panel, tileLevelValue);
     }
     void IncreaseScrollViewWindowSize(GameObject scrollViewContent, float prefabHieght)
     {
         scrollViewContent.GetComponent<RectTransform>().sizeDelta = new Vector2
         (
             scrollViewContent.GetComponent<RectTransform>().sizeDelta.x,
             scrollViewContent.GetComponent<RectTransform>().sizeDelta.y + prefabHieght
         );
     }
     void DecreaseScrollViewWindowSize(GameObject scrollViewContent, float prefabHieght)
     {
         scrollViewContent.GetComponent<RectTransform>().sizeDelta = new Vector2
         (
             scrollViewContent.GetComponent<RectTransform>().sizeDelta.x,
             scrollViewContent.GetComponent<RectTransform>().sizeDelta.y - prefabHieght
         );
     }
     void ResetScrollViewWindowSize(GameObject scrollViewContent, float basePadding = 5)
     {
         scrollViewContent.GetComponent<RectTransform>().sizeDelta = new Vector2
         (
             scrollViewContent.GetComponent<RectTransform>().sizeDelta.x,
             basePadding
         );
     }
 }

Just a little bit of code i wrote for you for you to scan over. not sure if this is what you were looking to do or not but its a nice list generator.

Comment

People who like this

0 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image zereda-games · 3 days ago 0
Share

Maybe add a public Text Component reff on the MyPrefab Script so you can display it in the scene (sorry forgot that)

That's pretty simple. Under the "prefabsList.Add(prefabCopy);" under AddPrefab(); you can put a

"prefabCopy.GetComponent().tileLevelText.text = GetTileLevel(prefabsList.Count) "

because AddPrefab(); is used 1 time in 'CreateNewPrefabScenePrefabOnList'.

avatar image zereda-games · 3 days ago 0
Share

Edited out my suggestions.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Update about the future of Unity Answers

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta later in June. Please note, we are aiming to set Unity Answers to read-only mode on the 31st of May in order to prepare for the final data migration.

For more information, please read our full announcement.

Follow this Question

Answers Answers and Comments

206 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Instantiate new object from scratch 1 Answer

Change Variable on Another Script 2 Answers

How can I set a Transform Variable in a Prefab? 1 Answer

How do I reset a script's values at run time to what they were at start? 3 Answers

[Solved]Instantiating prefab from a script and destroy it from another one 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges