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 jeffreymarasigan · Jan 25, 2015 at 08:52 AM · ienumeratorcreateobstaclegenerateobjectpool

Need help with my #c script to Generate 2 Obstacles

This code bellow is working for the one Obstacle1 prefab this is what happens when its working for obstacle1. obstacle1 generates off screen on right moves left then off screen then disappears and continues back to the beginning.

Im new in making games... I have this script GenerateObstacles.cs file that is working and it automatically generates Obstacle1 prefab. I've been trying to figure out how to add "Obstacle2" with a different float wait time. I've tried to make it work. Then when i go to test run the game the screen blinks and dose nothing. Need help please and thank you.


         using UnityEngine;
         using System.Collections;
        
         public class GenerateObstacles : MonoBehaviour {
        
             void Start () {
                 StartCoroutine("CreateObstacle");
             }
        
             IEnumerator CreateObstacle() {
                 float waitTime = 2.5f;
                 while(true) {
                     ObjectPool.instance.GetObjectForType("Obstacle1", true);
                     yield return new WaitForSeconds(waitTime);
                 }
             }
         }
      
 

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 Fornoreason1000 · Jan 25, 2015 at 10:31 AM 0
Share

there is something seriously wrong with your co routine, you do realize a while(true) statement will loop indefinitely right? in this case every 2.5 seconds ... forever,

also can you show me how you've we been trying to make "obstacle2" appear? and what is in this object Pool class? you clearly have some sort of singleton going on there. and some casting/ get reference function...

the main reason Obstacle2 doesn't appear because you never reference it at all. what do you mean by "add"? do you mean instantiate it? or add it to the pool so it can be used.

Are you new to C# program$$anonymous$$g as well as Game Development? if so did you take a tutorial on Object pooling ?

http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling

basically your co routine is an endless loop (which is bad for creating an object).

I can't help you unless you tell me how ObjectPool class and GetObjectForType function works

avatar image jeffreymarasigan · Jan 25, 2015 at 08:24 PM 0
Share

Thank you for your quick reply. I posted my ObjectPool.cs. Obstacle.cs I assign to my object obstacle1 prefab. Just waiting for approval by a moderator so you can view it.

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by jeffreymarasigan · Jan 25, 2015 at 08:49 PM

Thank you for the quick reply and yes I am new to C# programing. This is my ObjectPool.cs


 using System.Collections;
 using System.Collections.Generic;
 
 public class ObjectPool : MonoBehaviour {
 
     public static ObjectPool instance;
     public GameObject[] objectPrefabs;
     public List<GameObject>[] pooledObjects;
     public int[] amountToBuffer;
     protected GameObject containerObject;
 
     void Awake() {
         instance = this;
     }
 
     void Start() {
         containerObject = new GameObject("ObjectPool");
         pooledObjects = new List<GameObject>[objectPrefabs.Length];
         int i = 0;
         for(int j = 0; j < objectPrefabs.Length; j++) {
             pooledObjects[i] = new List<GameObject>();  
             int bufferAmount = amountToBuffer[i];
             for(int n = 0; n < bufferAmount; n++) {
                 GameObject newObj = Instantiate(objectPrefabs[j]) as GameObject;
                 newObj.name = objectPrefabs[j].name;
                 PoolObject(newObj);
             }
             i++;
         }
     }
     
     public GameObject GetObjectForType(string objectType, bool onlyPooled) {
         for(int i = 0; i < objectPrefabs.Length; i++) {
             GameObject prefab = objectPrefabs[i];
             if(prefab.name == objectType) {
                 if(pooledObjects[i].Count > 0) {
                     GameObject pooledObject = pooledObjects[i][0];
                     pooledObjects[i].RemoveAt(0);
                     pooledObject.transform.parent = null;
                     pooledObject.SetActive(true);
                     return pooledObject;
                 } else if(!onlyPooled) {
                     return Instantiate(objectPrefabs[i]) as GameObject;
                 }
                 break;
             }
         }
         return null;
     }
 
     public void PoolObject(GameObject obj) {
         for(int i = 0; i < objectPrefabs.Length; i++) {
             if(objectPrefabs[i].name == obj.name) {
                 obj.SetActive(false);
                 obj.transform.parent = containerObject.transform;
                 pooledObjects[i].Add(obj);
                 return;
             }
         }
     }
 
 }

And this is Obstacle.cs I assign to my object obstacle1 prefab.

 using System.Collections;
 
 public class Obstacle : MonoBehaviour {
 
     public Vector3 velocity = new Vector3(-2.5f, 0);
     public AudioClip sound;
     private Transform cachedTransform;
     private bool hasEnteredTrigger = false;
 
     void Awake() {
         cachedTransform = transform;
     }
     
     void Update() {
         cachedTransform.Translate(velocity * Time.smoothDeltaTime);
         if(!isVisible()) {
             Deactivate();
         }
     }
 
     void OnEnable() {
         cachedTransform.position = new Vector3(11, Random.Range(-3.0f, 3.0f), 5);
     }
 
     void OnDisable() {
         cachedTransform.position = new Vector3(-9999, 0, 5);
         hasEnteredTrigger = false;
     }
 
     bool isVisible() {
         bool result = true;
         Vector2 screenPosition = Camera.main.WorldToScreenPoint(cachedTransform.position);
         if(screenPosition.x < -100) {
             result = false;
         }
         return result;
     }
 
     void Deactivate() {
         ObjectPool.instance.PoolObject(gameObject);
     }
 
     void OnTriggerEnter2D(Collider2D other) {
         if(hasEnteredTrigger == false && other != null && other.CompareTag("Player")) {
             Score.TotalScore += 1;
             AudioSource.PlayClipAtPoint(sound, new Vector3(0, 0, 0), 1.0f);
             hasEnteredTrigger = true;
         }
     }
 
 }
 


Thank you for your time and help...

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 JakeTBear · Oct 13, 2015 at 03:09 PM 0
Share

Just by quickly looking at your pool class I could tell that your flag "onlyPooled", if set to true and if you dont buffer the Obstacle2 prefab in your hierarchy you wont be able to create any instances of it.

I would recommend getting rid of this flag and let your pool decide whether to create a new element or not. everything else looks right. (but highly inefficient)

avatar image
0

Answer by syedzia · Oct 13, 2015 at 01:11 PM

using UnityEngine; using System.Collections;

public class genarate : MonoBehaviour {

 public GameObject rocks;
 
 // Use this for initialization
 void Start()
 {
     InvokeRepeating("CreateObstacle", 1f, 1.5f);
 }
 
 void CreateObstacle()
 {
     Instantiate (rocks);
 }

}

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Random enemy generator 1 Answer

How to have IEnumerators run but not in Update 2 Answers

The right way to generate levels like Knife Hit or Paint hit game style. 1 Answer

Is there a message/event that I can wait for when object is created in the scene ? 0 Answers

Generating a cube mesh with two given points 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