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
0
Question by ger122 · Dec 13, 2014 at 03:18 PM · spawnnullreferenceexceptionspawnpoints

Random Spawn is NOT spawing Randomly,its always at SAME location ?

Random Spawn is NOT spawing Randomly, it spawns always at SAME location ? Why is this happening?

THIS IS A 2D GAME javascript I am now getting this error and when hilited it marks the last code line around instantiate..

 NullReferenceException: Object reference not set to an instance of an object
 vid.Spawn () (at Assets/cook/Animations/vid.js:30

I have script attached and object name is correct im pretty sure this is an easy fix but I cant seem to find what

heres the entire code below

this is a 2d game

 //var playerHealth : PlayerHealth;       // Reference to the player's heatlh.
 var fly : GameObject;                // The enemy prefab to be spawned.
 var spawnTime : float = 3f;            // How long between each spawn.
 var spawnPoints : Transform[];         // An array of the spawn points this enemy can spawn from.
 
 
 function Start ()
 {
     // Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
     InvokeRepeating ("Spawn", spawnTime, spawnTime);
 }
 
 //function OnCollisionEnter2D(coll : Collision2D) {
        
         // if (coll.gameObject.tag == "Enemy") {
          
 function Spawn ()
 {
      /*    
     //if(playerHealth.currentHealth <= 0f)
     
         // ... exit the function.
         return;
     }*/
 
     // Find a random index between zero and one less than the number of spawn points.
     var spawnPointIndex : int = Random.Range (0, spawnPoints.Length);
 
     // Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
     Instantiate (fly, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
 
 }
Comment
Add comment · Show 2
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 ger122 · Dec 14, 2014 at 03:18 PM 0
Share

I think I corrected it but want to be sure

heres what I put as of now

 var fly : GameObject;                // The enemy prefab to be spawned.
  var spawnTime : float = 3f;            // How long between each spawn.
  var spawnPoints : GameObject[];         // An array of the spawn points this enemy can spawn from.
   
   
   function Start ()
   {
       spawnPoints = GameObject.FindGameObjectsWithTag("SpawnLocations");
       // Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
       InvokeRepeating ("Spawn", spawnTime, spawnTime);
   } 
  
            
   function Spawn()
    {
        var spawnGameObject = spawnPoints[range(0,spawnPoints.Length-1)].transform;
        Instantiate (fly, spawnGameObject.position, spawnGameObject.rotation);
    }

avatar image ger122 ger122 · Dec 14, 2014 at 02:31 PM 0
Share

I think I corrected it but want to be sure

heres what I put as of now

  var fly : GameObject;                // The enemy prefab to be spawned.
   var spawnTime : float = 3f;            // How long between each spawn.
   var spawnPoints : GameObject[];         // An array of the spawn points this enemy can spawn from.
    
 5.   
    function Start ()
    {
        spawnPoints = GameObject.FindGameObjectsWithTag("SpawnLocations");
        // Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
 10.       InvokeRepeating ("Spawn", spawnTime, spawnTime);
    } 
   
             
    function Spawn()
 15.    {
         var spawnGameObject = spawnPoints[range(0,spawnPoints.Length-1)].transform;
         Instantiate (fly, spawnGameObject.position, spawnGameObject.rotation);
     }

6 Replies

· Add your reply
  • Sort: 
avatar image
-1

Answer by Ericool · Dec 13, 2014 at 05:10 PM

look at your Vid script : the size of your array is only 1 !

Comment
Add comment · Show 3 · 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 ger122 · Dec 13, 2014 at 10:02 PM 0
Share

hi yes but the code is for a random spawning do I need even 1 of them? I assumed if I put any it will be specific

Please remember I put one in the array /elements but I then started trying without any because it is meant to be a random spawning

Please guide me in what is correct way for random spawning as my code is for

Thanks im here

avatar image DryTear · Dec 14, 2014 at 06:17 PM 0
Share

Populate your array and it wont be so random. Or you can do :

Vector3 spawnPoint = new Vector3(Random.Range(-10,10), 2, Random.Range(-10,10));

avatar image ger122 · Dec 14, 2014 at 06:31 PM 0
Share

where should I put this piece of code under spawn function or ? please specify

avatar image
0

Answer by Antony-Blackett · Dec 13, 2014 at 03:20 PM

Removed as it was misinformation.

Comment
Add comment · Show 4 · 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 Bunny83 · Dec 13, 2014 at 03:30 PM 0
Share

That's not the problem as the integer version of Random.Range returns values $$anonymous$$-inclusive and max-exclusive. Also if that would be the issue you wouldn't get a Null-reference exception but an index out of bounds exception.

avatar image Antony-Blackett · Dec 13, 2014 at 03:33 PM 0
Share

Heh, so it does. Strange... I'm not sure what it is then.

avatar image Antony-Blackett · Dec 13, 2014 at 03:34 PM 1
Share

Are you sure you don't have any null objects in your spawn points transforms array? The only other thing it might be is the fly object might be null.

avatar image ger122 · Dec 13, 2014 at 03:49 PM 0
Share

when you say null you mean nothing correct? also this is a random spawning script do I have to have a spawns point transforms array?

Do I have to attach this script to the fly, or to the spawn empty gamneobject or to the background since I want a random spawn ?

I also get this error now

IndexOutOfRangeException: Array index is out of range. vid.Spawn () (at Assets/cook/Animations/vid.js:25)

avatar image
0

Answer by Bunny83 · Dec 13, 2014 at 03:38 PM

There are exactly two things that can be null in line 30:

  • Your fly reference

  • One of your spawnPoints references.

So make sure, at runtime, that your script has something assigned to the fly variable and that you don't have empty / null elements in your spawnPoints array.

Keep in mind that references become null if the object that is referenced is destroyed. So make sure you check the references in the inspector at runtime. If one is null or has become null you have to find the cause of that.

Comment
Add comment · Show 11 · 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 ger122 · Dec 13, 2014 at 03:47 PM 0
Share

I also get this error now

IndexOutOfRangeException: Array index is out of range. vid.Spawn () (at Assets/cook/Animations/vid.js:25)

please keep in $$anonymous$$d I am trying options here so I can go back n forth between settings trying to figure this out I had the spawn empty gameobj in array in the inspector then I left it empty also I tried the background as the element

I now get spawning but it is NOT RANDO$$anonymous$$ it is same locations every time

Do I have to attach this script to the fly, or to the spawn empty gamneobject or to the background since I want a random spawn ?

avatar image ger122 · Dec 13, 2014 at 04:53 PM 0
Share

Also here is a screen shot of the gameobjects inspector

Again I messed with script and inspector and spawns but not randomly and always at the same location.

avatar image Antony-Blackett · Dec 14, 2014 at 12:12 AM 1
Share

That's because you only have 1 transform in your spawn points array to choose from.

avatar image Antony-Blackett · Dec 14, 2014 at 01:27 AM 1
Share

I just realised you're using Java, my code is C#, Here's the java version (not tested). This code should replace everything you have inside your Spawn function.

 function Spawn()
 {
     var range : Vector3 = new Vector3(10,10,0);
     var randomPosition : Vector3 = new Vector3( Random.value*range.x, Random.value*range.y, 0 ); // z is 0 because you're making a 2D game.
     Instantiate (fly, randomPosition, Quaternion.Identity); // Quaternion.Identity is the same as saying 0 x, 0 y, and 0 z rotation.
 }
avatar image Antony-Blackett · Dec 14, 2014 at 04:26 AM 1
Share

Sorry, my initial comment had an error in it, but i corrected it, seems you got the original version though. look at my previous comment to see the correct code.

Show more comments
avatar image
0

Answer by Ericool · Dec 14, 2014 at 01:50 AM

You should Instantiate flies with an empty gameObject and each flies have a script with OnTriggerEnter that calls the empty gameObject method Spawn().

Comment
Add comment · 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 ger122 · Dec 14, 2014 at 01:55 AM 0
Share

I have a emty object named spawn but though tbecause this is a random script to get a random spawn I fi put it in a specific made spawn wont it spawn form there only?

heres what I have in inspector this is on the bad guy his name is fly so this scripts should be on the spawn point you think? please clarify

alt text

bbbb.jpg (80.5 kB)
avatar image
0

Answer by Corentin · Dec 14, 2014 at 01:22 PM

It seems that you don't store your spawn points in spawnPoints array. This array is empty so it's length is 0. Thus your spawnId is 0 and spawnPoints[0] is null. You should first initialize this SpawnPoints array (in Start() probably), maybe like this : spawnPoints = GameObject.FindGameObjectsWithTag("SpawnLocations"); This means you should give your SpawnPoints a tag.

PS : Or maybe you initialize this array in the inspector ?

Comment
Add comment · Show 13 · 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 ger122 · Dec 14, 2014 at 01:35 PM 0
Share

Hi this is script I have

Can you tell me where to put it I tried placing under start function but got an error , can you copy and post the full code of these 2 ($$anonymous$$e and yours) so I can see details matter with scripting

Assets/Scripts/hy.js(19,49): BCE0022: Cannot convert 'UnityEngine.GameObject[]' to 'UnityEngine.Transform[]'.

this is code I currently have $$anonymous$$us your new part

  var fly : GameObject;                // The enemy prefab to be spawned.
 var spawnTime : float = 3f;            // How long between each spawn.
 var spawnPoints : Transform[];         // An array of the spawn points this enemy can spawn from.
 
 
 function Start ()
 {
 
 
 
 
     // Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
     InvokeRepeating ("Spawn", spawnTime, spawnTime);
 }
 {spawnPoints = GameObject.FindGameObjectsWithTag("SpawnLocations"); 
 
 }
 //function OnCollisionEnter2D(coll : Collision2D) {
        
         // if (coll.gameObject.tag == "Enemy") {
          
 function Spawn()
  {
      var range : Vector3 = new Vector3(10,10,0);
      new Vector3( Random.value*range.x, Random.value*range.y, 0 ); // z is 0 because you're making a 2D game.
      Instantiate (fly, Random.Position, Quaternion.Identity); // Quaternion.Identity is the same as saying 0 x, 0 y, and 0 z rotation.
  }
 
    

avatar image ger122 · Dec 14, 2014 at 01:39 PM 0
Share

the error is because your new code part mentions spawnpoints as a gameobject but I have as a transform so which is correct one I should choose?

avatar image Corentin · Dec 14, 2014 at 01:44 PM 0
Share

You were going the right way ! You should read carefully the error "Cannot convert 'UnityEngine.GameObject[]' to 'UnityEngine.Transform[]'." What it means is that you have an array of GameObjects, when you need an array of Transform components (this was a mistake on my side). So you can either convert this array to transforms , or store gameObjects ins$$anonymous$$d. I wish I could show you how to do this, but I never did js before. You could store a GameObject array, and do a foreach( var go in spawnObjects) to take go.transform and put it inside spawnPoints

PS: You answered again while I was writing this , sorry

avatar image Corentin · Dec 14, 2014 at 01:45 PM 0
Share

all this should be done inside Start method

avatar image ger122 · Dec 14, 2014 at 02:14 PM 0
Share

what is the difference between using gameobjects and transforms?

What ever you recommend I will try so I think you mean do as gameobjects correct , that is what I will try. I will try and get rite back to you

don't worry if you can explain to me I can do it I also wish you could show me can u record a video on your pc? a visual would really help just to cut out any mistakes

Show more comments
  • 1
  • 2
  • ›

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

7 People are following this question.

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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Spawning PreScripted Objects... 2 Answers

NullReferenceException: Object reference not set to an instance of an object 1 Answer

very weird NullReferenceException error causeing one script to break another 2 Answers

instatiate prefabs at start, at a spawn point 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