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 dark_reaper · Jan 20, 2014 at 05:03 PM · rigidbodydestroyenemyspawn

Need help with enemy spawner

Hi guys,

Iv been trying to make a spawner for my enemies but iv hit a wall. At the moment I have a object (with a script) that deals with the spawning of the enemies and I have a script connected to the enemy object that makes it move towards the player. The problem is that when I destroy all the enemy objects, I cant spawn any more cuz there is no rigidbody to clone. I not sure what to do so any help would be very appreciated (still new to unity).

The following if the code that is in the enemy's and the code in the spawner.

enemy's code

 using UnityEngine;
 using System.Collections;
 
 public class enemyscript : MonoBehaviour {
     
     float speed = 2.0f;    
 
 
     // Use this for initialization
     void Start () {
 
     }
     
     // Update is called once per frame
     void Update () 
     {
         movement();
     }
 
     void movement()
     {
     transform.position = Vector3.MoveTowards(transform.position,GameObject.Find("player").transform.position,speed * Time.deltaTime);
 
     }
     
 
     void OnTriggerEnter(Collider other)
     {
         if(other.gameObject.tag == "Player" || other.gameObject.tag == "bullet")
         {
             Destroy(gameObject);
         }
     }
     
 }

spawner code

 using UnityEngine;
 using System.Collections;
 
 public class enemyspawnman : MonoBehaviour {
     
     public Rigidbody Enemyprefeb;
 
     float delay = 5.0f;
 
     float canspawn = 5;
 
     public float randx, randy, randz;
 
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
 
         enemyspawn ();
     
     }
     public void enemyspawn()
     {
         if (Time.time >= canspawn) 
         {
             randx = Random.Range(-7.0f,7.0f);
             randy = Random.Range(-3.0f,4.0f);
             randz = Random.Range(4.0f,5.0f);
 
         Enemyprefeb = Instantiate (Enemyprefeb, new Vector3(randx,randy,randz), transform.rotation) as Rigidbody;
             canspawn += delay;
         }
 
         
     }
     
 }
 
 
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
0
Best Answer

Answer by Exalia · Jan 20, 2014 at 07:30 PM

Take the Enemy you are cloning currently and save it as a prefab

(Drag it from the Hierarchy to the Project tab)

Now your Enemy is saved as a prefab.

In your script change your public rigidbody to a public GameObject.

In the editor drag the prefab (From the Project View) into the public GameObject slot in the Inspector Tab

Your spawner will now clone the prefab instead of a preexisting GameObject in the scene

Here is a copy of a spawner script I use, be aware of the disclaimer at the top of the code.

 /*
  * This confidential and proprietary software may be used only as
  * authorised by a licensing agreement from ARM Limited
  * (C) COPYRIGHT 2014 ARM Limited
  * ALL RIGHTS RESERVED
  * The entire notice above must be reproduced on all authorised
  * copies and copies may only be made to the extent permitted
  * by a licensing agreement from ARM Limited.
  */
 
 using UnityEngine;
 using System.Collections;
 
 public class SpawnerScript : MonoBehaviour 
 {
     //Public Variables
     public GameObject prefabToSpawn;
     public float spawnTime;
     public float spawnTimeRandom;
     //Private Variables
     private float spawnTimer;
 
     //Used for initialisation
     void Start () 
     {
         ResetSpawnTimer();
     }
     
     //Update is called once per frame
     void Update () 
     {
         spawnTimer -= Time.deltaTime;
         if (spawnTimer <= 0.0f)
         {
             Instantiate(prefabToSpawn, transform.position, Quaternion.identity);
             ResetSpawnTimer();
         }
     }
 
     //Resets the spawn timer with a random offset
     void ResetSpawnTimer()
     {
         spawnTimer = (float)(spawnTime + Random.Range(0, spawnTimeRandom*100)/100.0);
     }
 }
 

I hope this helps

P.S : A little tip for the future, avoid using .tag, use CompareTag() instead, ontop of that avoid FindObject or FindObjects, this is really inefficient especially when done on an Update. Try and define as much as possible using the inspector and public variables to avoid searching through every object in your scene unnecessarily

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 dark_reaper · Jan 20, 2014 at 08:09 PM 0
Share

That works. Thanks for the help and the tip :)

avatar image Exalia · Jan 20, 2014 at 08:19 PM 0
Share

You're very welcome, feel free to mark the question as answered by the way :)

avatar image nicoguerra1337 · Nov 12, 2014 at 09:37 PM 0
Share

I had the same problem, but I used your script and it worked. The enemy I'm trying to spawn uses a Nav$$anonymous$$eshAgent, and when it spawns the Nav$$anonymous$$eshAgent doesnt work and I get this warning :

 Failed to create agent because it is not close enough to the Nav$$anonymous$$esh
avatar image
0

Answer by robertbu · Jan 20, 2014 at 05:07 PM

When doing this spawning, use a true prefab, not a scene object. Prefabs are like blueprints, and don't exist in the scene. More info:

http://docs.unity3d.com/Documentation/Manual/Prefabs.html

Then in your scene, you don't assign the results of your Instantiate to your prefab. So leave out the 'Enemyprefab =' on line 34.

Comment
Add comment · Show 7 · 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 dark_reaper · Jan 20, 2014 at 06:30 PM 0
Share

Iv made the enemy a prefab now but if i take away the 'Enemyprefab =' I get an error since it does not know what to duplicate. Would I move this script onto the enemy true prefab?

avatar image robertbu · Jan 20, 2014 at 07:12 PM 0
Share

What you say doesn't make sense given the changes I recommend. Please post your amended script and the a copy of the error. You still leave 'public Enemyprefab;' at the top of the file, and you initialize this variable with the true prefab you created. You just don't assign the result of the Instantiate back to the 'EnemyPrefab' variable.

avatar image dark_reaper · Jan 20, 2014 at 08:17 PM 0
Share

so iv changed the line to Instantiate (Enemyprefeb, new Vector3(randx,randy,randz), transform.rotation); and the enemy is a prefab.

the error I when i destroy it is "the object type rigidbody has been destroyed but you are still trying to access it" (since i'm destroying the original still)

avatar image Exalia dark_reaper · Jan 20, 2014 at 08:20 PM 0
Share

You need to destroy the GameObject, not the rigidbody. The Rigidbody is an attribute of the GameObject

avatar image robertbu · Jan 20, 2014 at 08:23 PM 0
Share

This is a separate issue. Nothing in the scripts above attempt to accessing anything in the Rigidbody component. Whatever script is generating this error, need to reacquire the the rigid body either when the current one is destroyed or alternately every frame.

Note if you are always going to be spawning a new copy of this prefab right after the original is destroyed, and alternate solution is to simply move the rigid body to a new position and reset any state to the initial state of the object. This would solve your reference problem since the object is never destroyed.

avatar image Exalia · Jan 20, 2014 at 08:42 PM 0
Share

public Rigidbody Enemyprefeb;

dark_reaper IS accessing the Rigidbody component

Secondly, robertbu's suggestion is also great from optimisation, Instantiate is an expensive function, better to transform to a position out of sight, reset all variables and prepare to reuse the GameObject.

Show more comments

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

19 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

Related Questions

change script so enemy car gets destroyed when collided with player car 0 Answers

Destroy Enemy Rigidbody after Jumping on Head? 3 Answers

Melle system destroy game object not working despite no errors and declining health 1 Answer

Spawner continuing after boss dies 1 Answer

Enemy's wont die if spawned 1 Answer


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