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 SantiN90 · Oct 19, 2010 at 05:49 PM · instantiatewaitforsecondsshootautomaticendless

Problem with Auto instantiating in X seconds in C#

Hi! I'm new to Unity and C# and wanted a little help with this little Script of mine.

I'm not quite sure if the title is explicit.

So, what I want to achieve is, basically:

I have an enemy with a Gun attached to it. This gun has an empty GameObject that should be "shooting" prefabs forward and there should be some time (set by myself) between every shot. Ten seconds after the bullet has been shot, it is destroyed.

I have achieved this in my FirstPersonController with right mouse click. But I can't seem to make it automatically.

My question is, if I instantiate the enemies when going through a trigger, how can I make them start shooting automatically after being instantiated, given an X time between shots?

NOTE: The enemies should just shoot forward, not aiming or anything. And they'd have to do it endlessly.

This is what I have so far.

using UnityEngine; using System.Collections;

public class EnemyShootScript : MonoBehaviour { public Rigidbody EnemyBullet; public int speed = 50; public int ShootTime = 5;

// Use this for initialization void Start () {

}

// Update is called once per frame void Update (){

 if(Input.GetButtonDown("Fire2")){ //This is where there should be the automatic firing code
 Rigidbody EnemyAmmo  = Instantiate (EnemyBullet, transform.position, transform.rotation) as Rigidbody;

 EnemyAmmo.velocity = transform.TransformDirection(new Vector3(0,0,speed));

 Destroy(EnemyAmmo.gameObject, 10); //I destroy the bullet after 10 seconds
 }

} }

I've also tried using WaitForSeconds, but I just can't seem to entirely get it, though.

If someone could help me with this, I'd be really thankful.

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

1 Reply

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

Answer by skovacs1 · Oct 19, 2010 at 07:24 PM

This is very simple. WaitForSeconds is the way to go.

ShootScript.cs

using UnityEngine; using System.Collections;

public class ShootScript : MonoBehaviour { public float timeBetweenShots = 5.0f; public Rigidbody bullet; public float bulletSpeed = 500; public float bulletLifetime = 10.0f; public bool shooting = true;

 void Start() {
     StartShooting();
 }

 void StartShooting() {
     shooting = true;
     StartCoroutine("TimedShooting");
 }

 IEnumerator TimedShooting() {
     while(shooting) {
         if(bullet) {
             Rigidbody newBullet = Instantiate(bullet, transform.position, 
                                       transform.rotation) as Rigidbody;
             newBullet.AddForce(transform.forward * bulletSpeed);
             Physics.IgnoreCollision(collider, newBullet.collider);
             Destroy(newBullet.gameObject, bulletLifetime);
             yield return new WaitForSeconds(timeBetweenShots);
         }
     }
 }

}

To create your own timed destruction, you could also use WaitForSeconds:

AutoDestruct.cs

using UnityEngine; using System.Collections;

public class AutoDestruct : MonoBehaviour { public float lifetime = 10.0f; void Start() { StartCoroutine("TimedDestruct") }

 IEnumerator TimedDestruct() {
     yield return new WaitForSeconds(lifetime);
     Destroy(gameObject);
 }

}

or not

AutoDestruct.cs

using UnityEngine;

public class AutoDestruct : MonoBehaviour { public float lifetime = 10.0f; void Start() { Destroy(gameObject, lifetime); } }

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 SantiN90 · Oct 19, 2010 at 10:13 PM 0
Share

Hey, thanks for the quick response!

One thing, though. I tried your code.. but it seems to had flooded one of my cores. I had to ter$$anonymous$$ate the Unity process.

I re-checked your code but I don't seem to find the cause of the stacking.

I'll keep tinkering here. If you find what's causing it, let me know. :)

Thanks again.

avatar image skovacs1 · Oct 19, 2010 at 10:46 PM 0
Share

Yeah, a little too quick - had some typos that I've since fixed. It's your physics that's crashing your Unity. Your bullets are colliding with the one shooting them. You can either ignore collision between the two (as I have updated the script to do), remove the collider from the shooter or offset your instantiate so that it is not inside your shooter's collider.

avatar image SantiN90 · Oct 19, 2010 at 11:05 PM 0
Share

Well, I've been playing with it. I changed some stuff, like the "newBullet.AddForce(transform.forward * bulletSpeed);" for "newBullet.velocity = transform.TransformDirection(new Vector3(0,0,speed));" using the "public float speed = 50;" I had earlier. It seems to be working almost perfectly now. Except for some cases in which a core gets stacked. Well, Thank you very much for your help. It is much appreciated. :) See you around.

avatar image skovacs1 · Oct 20, 2010 at 02:23 PM 0
Share

The reason I went with AddForce over velocity= is because the docs state that velocity= can create "unrealistic behaviour". Either way, the net effect is the same if you adjust your forces and neither will actually take effect until the next FixedUpdate anyways. To debug your crashing you could try something like "function OnCollisionEnter(collision : Collision) { Debug.Log(collision.gameObject.name); }" in a script on your bullets to tell you what you are colliding with.

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

No one has followed this question yet.

Related Questions

Trying to get a shoot function working in unity using instantiate and it isn't working. 1 Answer

Endless Prefab Instantiating with different position and rotation 1 Answer

Problem with Network.Instantiate on instantiating a bullet. 1 Answer

Yeild and WaitForSeconds and Instantiate 1 Answer

Abstract Class - Monobehaviour Functions 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