- Home /
How to set prefab's script value programatically?
Hello! I have a prefab like "Level1.prefab" and I have a component attached to it, in this case, Category.
I want to multiply levels prefab and set "Category Name" and "Category Icon" programatically like from a shell.
How can I do this?
Hi, I'm assu$$anonymous$$g you need to make clones of your prefab and assign different values. You can use another script to clone the Level prefab and assign the required values. Something like this.
//The Category script
public class Category : $$anonymous$$onoBehaviour
{
public string CategoryName;
public Sprite CategoryIcon;
}
You can use another script with the prefab script dragged and dropped to this. And call NewLevel() function with values whenever required
public class Levels : $$anonymous$$onoBehaviour
{
//Reference to the prefab object with the Category script attached
public Category prefab;
//Function to clone a new prefab
public void NewLevel(string name, Sprite icon)
{
//Clone new prefab and get the Category script component reference
Category nCat = Instantiate(prefab).GetComponent<Category>();
//Set the new name
nCat.CategoryName = name;
//Set the new icon
nCat.CategoryIcon = icon;
}
}
Answer by text23d · Nov 30, 2017 at 08:18 PM
Category CategoryScript = gameobject.GetComponent(); CategoryScript .CategoryName="Level 2"; //etc
Your answer
Follow this Question
Related Questions
scripting and prefab saving error 0 Answers
Execute code once when a prefab is placed into the scene? 2 Answers
Change script from EditorWindow 0 Answers
How to run script in editor 1 Answer
Script on prefab keeps values from one execution to another 1 Answer