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
0
Question by Chocolade · Jun 03, 2017 at 11:33 AM · c#scripting problemscript.pooling

How can i use the object pool script to create and destroy gameobjects ?

The ObjectPool script:

 using UnityEngine;
 using System.Collections.Generic;
 
 public class ObjectPool
 {
     private GameObject prefab;
 
     private List<GameObject> pool;
 
     public ObjectPool(GameObject prefab, int initialSize)
     {
         this.prefab = prefab;
 
         this.pool = new List<GameObject>();
         for (int i = 0; i < initialSize; i++)
         {
             AllocateInstance();
         }
     }
 
     public GameObject GetInstance()
     {
         if (pool.Count == 0)
         {
             AllocateInstance();
         }
 
         int lastIndex = pool.Count - 1;
         GameObject instance = pool[lastIndex];
         pool.RemoveAt(lastIndex);
 
         instance.SetActive(true);
         return instance;
     }
 
     public void ReturnInstance(GameObject instance)
     {
         instance.SetActive(false);
         pool.Add(instance);
     }
 
     protected virtual GameObject AllocateInstance()
     {
         GameObject instance = (GameObject)GameObject.Instantiate(prefab);
         instance.SetActive(false);
         pool.Add(instance);
 
         return instance;
     }
 }

And the script i'm using to create the gameobjects. This script is attached to a empty GameObject. The part that create the gameobjects in the Clone() is working fine with the pooling.

The problem is in the Update()

I want that when i change the value of SpaceShipCount in the Inspector while the game is running in real time to remove/release/destroy all the already existing gameobjects and create new once according to the new value of SpaceShipCount.

And i don't want it to be like a gun bullet effect i want all the gameobjects to release at once and then to create the new once.

The problem is that when i change the SpaceShipCount value it's releasing(destroying) only one object. For example if i'm running the game and i have 100 objects when i change the SpaceShipCount value to 1 i want to have 1 new gameobject but not gun bullet shooting effect but more like destroying effect. To release(destroy) all objects and create new.

 using System;
 using UnityEngine;
 using Random = UnityEngine.Random;
 using System.Collections;
 using System.Collections.Generic;
 using System.Linq;
 
 public class InstantiateObjects : MonoBehaviour
 {
     public GameObject Spaceship;
     public int spaceshipsStartingHeight = 20;
     [HideInInspector]
     public GameObject[] spaceships;
 
     // for tracking properties change
     private Vector3 _extents;
     private int _spaceshipCount;
     private float _spaceshipSize;
     private ObjectPool bulletPool;
     private GameObject o;
 
     /// <summary>
     ///     How far to place spheres randomly.
     /// </summary>
     public Vector3 Extents;
 
     /// <summary>
     ///     How many spheres wanted.
     /// </summary>
     public int SpaceShipCount;
     public float SpaceShipSize;
 
     // Use this for initialization
     void Start()
     {
         Clone();
     }
 
     private void OnValidate()
     {
         // prevent wrong values to be entered
         Extents = new Vector3(Mathf.Max(0.0f, Extents.x), Mathf.Max(0.0f, Extents.y), Mathf.Max(0.0f, Extents.z));
         SpaceShipCount = Mathf.Max(0, SpaceShipCount);
         SpaceShipSize = Mathf.Max(0.0f, SpaceShipSize);
     }
 
     private void Reset()
     {
         Extents = new Vector3(250.0f, 20.0f, 250.0f);
         SpaceShipCount = 100;
         SpaceShipSize = 20.0f;
     }
 
     // Update is called once per frame
     void Update()
     {
         if (_spaceshipCount != SpaceShipCount)
         {
             for (var i = 0; i < _spaceshipCount; i++)
             {
                 ReleaseBullet(o);
             }
             _spaceshipCount = SpaceShipCount;
             Clone();
         }
     }
 
     private void Clone()
     {
         if (Extents == _extents && SpaceShipCount == _spaceshipCount && Mathf.Approximately(SpaceShipSize, _spaceshipSize))
             return;
         
         var withTag = GameObject.FindWithTag("Terrain");
         if (withTag == null)
             throw new InvalidOperationException("Terrain not found");
 
         bulletPool = new ObjectPool(Spaceship, SpaceShipCount);
 
         for (var i = 0; i < SpaceShipCount; i++)
         {
             o = bulletPool.GetInstance();
             o.tag = "SpaceShip";
             o.transform.SetParent(base.gameObject.transform);
             o.transform.localScale = new Vector3(SpaceShipSize, SpaceShipSize, SpaceShipSize);
 
             // get random position
             var x = Random.Range(-Extents.x, Extents.x);
             var y = Extents.y; // sphere altitude relative to terrain below
             var z = Random.Range(-Extents.z, Extents.z);
 
             // now send a ray down terrain to adjust Y according terrain below
             var height = 10000.0f; // should be higher than highest terrain altitude
             var origin = new Vector3(x, height, z);
             var ray = new Ray(origin, Vector3.down);
             RaycastHit hit;
             var maxDistance = 20000.0f;
             var nameToLayer = LayerMask.NameToLayer("Terrain");
             var layerMask = 1 << nameToLayer;
             if (Physics.Raycast(ray, out hit, maxDistance, layerMask))
             {
                 var distance = hit.distance;
                 y = height - distance + y; // adjust
             }
             else
             {
                 Debug.LogWarning("Terrain not hit, using default height !");
             }
 
             //o.transform.Rotate(0.0f,randomNumbers[i],0.0f);
             // place !
             o.transform.position = new Vector3(x, y + spaceshipsStartingHeight, z);
         }
 
         _extents = Extents;
         _spaceshipCount = SpaceShipCount;
         _spaceshipSize = SpaceShipSize;
     }
 
     void ReleaseBullet(GameObject bullet)
     {
         bulletPool.ReturnInstance(bullet);
     }
 }
 
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

0 Replies

· Add your reply
  • Sort: 

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

334 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How do i use a public sealed class to create objects and destroy them ? 0 Answers

How can i use a button key click to switch/toggle between enum options ? 1 Answer

How can i make both two cameras to follow the player but only one with control on player ? 0 Answers

Why when i loop over the vertices it's not showing the mesh ? 1 Answer

When the mouse is moving and the player is walking why the player is stuttering ? 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