Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 prefix · Dec 13, 2015 at 02:54 PM · instantiatearrayrandom

C# Spawn Random Object, at Random 2D Location

Hello all! (struggling beginner coder here).

I want to Spawn a random object within an array, at a random spot in Vector2D space

Im still not quite understanding what im doing wrong. Thank you kindly in advance!


    //Array of objects to spawn
     public GameObject[] theGoodies;
     GameObject goods;
 
     //Time it takes to spawn theGoodies
     [Space(3)]
     public float waitingForNextSpawn = 10;
     public float theCountdown = 10;
 
     // the range of X
     [Header ("X Spawn Range")]
     public float xMin;
     public float xMax;
 
     // the range of y
     [Header ("Y Spawn Range")]
     public float yMin;
     public float yMax;
 
 
     void Start()
     {
         // goods now represents the random object within the array
         goods = theGoodies [Random.Range (0, theGoodies.Length)];
     }
 
 
 
     public void Update()
     {
         // timer to spawn the next goodie Object
         theCountdown -= Time.deltaTime;
         if(theCountdown <= 0)
         {
             SpawnGoodies ();
             theCountdown = waitingForNextSpawn;
         }
     }
 
 
     void SpawnGoodies()
     {
         // Defines the min and max ranges for x and y
         Vector2 pos = new Vector2 (Random.Range (xMin, xMax), Random.Range (yMin, yMax));
 
         // Creates the random object at the random 2D position.
         Instantiate (goods, pos) as GameObject;
     }
     
 }

Comment
Add comment · Show 1
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 sandeepsmartest · Dec 15, 2015 at 05:28 AM 2
Share

The issue with your code is that "goods " variable is assigned with the value only once that is at start method(Start method gets called only once in its life time as soon as you hit play button). Though the condition if(theCountdown

      void SpawnGoodies()
      {
          // Defines the $$anonymous$$ and max ranges for x and y
          Vector2 pos = new Vector2 (Random.Range (x$$anonymous$$in, x$$anonymous$$ax), Random.Range (y$$anonymous$$in, y$$anonymous$$ax));
   // goods now represents the random object within the array
          goods = theGoodies [Random.Range (0, theGoodies.Length)];
          // Creates the random object at the random 2D position.
          Instantiate (goods, pos) as GameObject;
      }

 
      

hope this may help you. NS$$anonymous$$S

2 Replies

· Add your reply
  • Sort: 
avatar image
4
Best Answer

Answer by wibble82 · Dec 15, 2015 at 11:19 AM

Your code appears largely correct, aside from 2 little issues:

  • You don't need the 'as GameObject' on the end of Instantiate. This is a 'dynamic cast'. If you wanted to store the result of instantiate you would need to cast it to a game object (though as you know for a fact it is a game object you would use the faster 'static cast')

  • You are only randomly choosing the 'goods' to spawn once.

Here's a tweaked version of that code:

    //Array of objects to spawn (note I've removed the private goods variable)
      public GameObject[] theGoodies;
  
      //Time it takes to spawn theGoodies
      [Space(3)]
      public float waitingForNextSpawn = 10;
      public float theCountdown = 10;
  
      // the range of X
      [Header ("X Spawn Range")]
      public float xMin;
      public float xMax;
  
      // the range of y
      [Header ("Y Spawn Range")]
      public float yMin;
      public float yMax;
  
  
      void Start()
      {
      }
  
      public void Update()
      {
          // timer to spawn the next goodie Object
          theCountdown -= Time.deltaTime;
          if(theCountdown <= 0)
          {
              SpawnGoodies ();
              theCountdown = waitingForNextSpawn;
          }
      }
  
  
      void SpawnGoodies()
      {
          // Defines the min and max ranges for x and y
          Vector2 pos = new Vector2 (Random.Range (xMin, xMax), Random.Range (yMin, yMax));
  
          // Choose a new goods to spawn from the array (note I specifically call it a 'prefab' to avoid confusing myself!)
          GameObject goodsPrefab = theGoodies [Random.Range (0, theGoodies.Length)];
 
          // Creates the random object at the random 2D position.
          Instantiate (goodsPrefab, pos);
 
          // If I wanted to get the result of instantiate and fiddle with it, I might do this instead:
          //GameObject newGoods = (GameObject)Instantiate(goodsPrefab, pos)
          //newgoods.something = somethingelse;
      }

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 prefix · Dec 17, 2015 at 04:15 AM 0
Share
     //Array of objects to spawn (note I've removed the private goods variable)
     public GameObject[] theGoodies;
 
     //Time it takes to spawn theGoodies
     [Space(3)]
     public float waitingForNextSpawn = 10;
     public float theCountdown = 10;
 
     // the range of X
     [Header ("X Spawn Range")]
     public float x$$anonymous$$in;
     public float x$$anonymous$$ax;
 
     // the range of y
     [Header ("Y Spawn Range")]
     public float y$$anonymous$$in;
     public float y$$anonymous$$ax;
 
 
     void Start()
     {
     }
 
     public void Update()
     {
         // timer to spawn the next goodie Object
         theCountdown -= Time.deltaTime;
         if(theCountdown <= 0)
         {
             SpawnGoodies ();
             theCountdown = waitingForNextSpawn;
         }
     }
 
 
     void SpawnGoodies()
     {
         // Defines the $$anonymous$$ and max ranges for x and y
         Vector2 pos = new Vector2 (Random.Range (x$$anonymous$$in, x$$anonymous$$ax), Random.Range (y$$anonymous$$in, y$$anonymous$$ax));
 
         // Choose a new goods to spawn from the array (note I specifically call it a 'prefab' to avoid confusing myself!)
         GameObject goodsPrefab = theGoodies [Random.Range (0, theGoodies.Length)];
 
         // Creates the random object at the random 2D position.
         Instantiate (goodsPrefab, pos, transform.rotation);
 
         // If I wanted to get the result of instantiate and fiddle with it, I might do this ins$$anonymous$$d:
         //GameObject newGoods = (GameObject)Instantiate(goodsPrefab, pos)
         //newgoods.something = somethingelse;
     }
 }
avatar image prefix · Dec 17, 2015 at 04:18 AM 0
Share

The following code is a complete functional result of the wonderful help I received from you all. The only thing that needed to be "added" was:

Instantiate (goodsPrefab, pos, transform.rotation);

It threw an error asking for 2 arguments.. so i put the "transform.rotation" in there and it works perfectly.. Thank you all!

avatar image
0

Answer by FAL0 · Dec 15, 2015 at 02:48 AM

     // Creates the random object at the random 2D position.
      Instantiate (goods, pos) as GameObject;

          as GameObject      

alt text


labueu.png (4.8 kB)
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 landon912 · Dec 15, 2015 at 02:47 AM 0
Share

@FAL0, I approved of your post, but it's not a very good answer. Please edit it with a solution and more details to avoid down votes.

avatar image LordDarkon76 · Dec 15, 2015 at 04:51 PM 0
Share

Just delete the as GameObject.

It is only used if the object is assigned.

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

8 People are following this question.

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

Related Questions

instantiate a random object from multiples via 'tag' 1 Answer

multiple object in multiple spawn Point with out repeat 0 Answers

Spawning Objects Using An Array. 1 Answer

How to instantiate the first 8 gameobjects in an array (UnityScript)? 1 Answer

Randomly instantiate objects from array without choosing the same item twice. 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