Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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
1
Question by GabeOfThrones · Dec 16, 2012 at 11:35 PM · gameobjectinstantiateprefab

How to instantiate a prefab with a script attached?

I've been searching for this for days now and feel stupid because it seems like it should be ridiculously simple...

My game requires me to create and destroy different characters in an environment. I have a prefab called "human" with an attached class "Human" that handles all of its attributes and behaviors.

At runtime I want to create a certain amount of these humans with randomized attributes. I've been searching through these forums for examples, but none of the code seems to work for what I'm doing. I feel like my problems are just syntax, but I've seen so many alternate solutions that haven't worked now that my mind is mud. Rather than copy code, I'm hoping someone can explain how this would ideally be done in Unity from scratch. Thanks for any help!

Comment
Add comment
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
1

Answer by Statement · Dec 17, 2012 at 12:37 AM

So let's take a time to think about your problem. You say that you have a human prefab. I will just picture this in my head as a character with a script on it that defines some attributes and leave out the exact details about how it's working inside. Just to give us something to think about in our coder heads, I will make a mock here with some properties that we want to change:

 public class Human : MonoBehaviour
 {
     // The thing we want to modify at runtime.
     public Attributes attributes;
     
     // More code that defines what humans do, 
     // like program awesome scripts or post
     // images about cats on facebook...
 }
 
 // The set of attributes that our human has access to.
 [System.Serializable]
 public class Attributes
 {
     [Range(0, 20)] public float strength = 10;
     [Range(0, 20)] public float dexterity = 10;
     [Range(0, 20)] public float intelligence = 10;    
 }

So, a prefab has it's defined values for strength, dexterity and intelligence. Depending on how you want to model your game and spawner logic, perhaps the spawner can decide what the attributes should be for the human and totally overwriting the values? Or perhaps your spawner has links to several different prefabs, so it chooses one of the prefabs when it should spawn a human? It's up to you, I'll try and explain how to make the attributes somewhere of a middle ground between fully designed attributes (hand crafted by a designer) and fully randomized values (binary grinded by computer).

So you could define two extremes of attributes that you want to generate values for, hopefully unique for every human that spawns. In this solution, you could pick a random value for strength, dexterity and intelligence that is defined by a min and a max attribute collection. See the code below:

 public class HumanSpawner : MonoBehaviour
 {    
     public Human prefab;
     [Range(0, 10)] public int humansToSpawn = 5;
     public Attributes min;
     public Attributes max;
     
     void Start ()
     {
         for (int i = 0; i < humansToSpawn; ++i) {
             Human human = (Human)Instantiate (prefab);
             human.attributes = MakeRandomAttributes ();
         }
     }
     
     // Have a better way of making random attributes? 
     // Perhaps you have a set of several templates instead,
     // carefully balanced by a designer? Then change this code.
     Attributes MakeRandomAttributes ()
     {
         Attributes result = new Attributes ();
         result.strength = Mathf.Lerp (min.strength, max.strength, Random.value);
         result.dexterity = Mathf.Lerp (min.dexterity, max.dexterity, Random.value);
         result.intelligence = Mathf.Lerp (min.intelligence, max.intelligence, Random.value);
         return result;
     }
 }

This is one way of doing it, but also consider having a public Human[] allPossiblePrefabs; and pick one of those instead, or any mix in between. It's up to you to define what you actually want to randomize. Then decide how you want to randomize it. Should it be finely controlled? Should it be emergent and chaotic?

Comment
Add comment · 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 Statement · Dec 17, 2012 at 12:49 AM 0
Share

Caveat: If you are on Unity 3.5, remove the [Range(x,y)] snippets. They are only available in Unity 4 and doesn't do anything more than add fancy sliders to the inspector.

avatar image wolis · Aug 03, 2014 at 08:14 PM 0
Share

O$$anonymous$$G. Can't thank you enough Statement, I had a similar question, but your way of organizing things helped me more than the answer to the question. Thank you!

avatar image
0

Answer by GabeOfThrones · Dec 17, 2012 at 01:52 AM

Wow. Thanks so much for answering so quickly and completely! I was able to solve the syntactical problem I was having immediately with your code!

The key line that I was botching was this:

 Human human = (Human)Instantiate (prefab);

It's interesting how you handled the attributes. I may try that style. Currently I was just simply trying to set properties of the Human class. For example:

 public class Human : MonoBehaviour
 {
     public int speed
 }

Once I've instantiated human, I try setting speed like:

 human.speed = 5;

I don't seem to have access to the object's properties. Do I need to do something additional to get access to those?

Again, thanks for the help, Statement!

Comment
Add comment · 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

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.

Follow this Question

Answers Answers and Comments

10 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

Related Questions

Referencing gameObject from script after Instantiate 0 Answers

autolink to prefab? 0 Answers

How many time does a prefab takes to load?? 1 Answer

Instantiate as a child on a certain point? 1 Answer

Save gameobjects prefabs from scene A to a list, then instantiate those game objects to another scene. 0 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