Skip to content

Instantly share code, notes, and snippets.

@Makizemi
Created October 17, 2018 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Makizemi/c059e1c69a30102941bcf0000cd22527 to your computer and use it in GitHub Desktop.
Save Makizemi/c059e1c69a30102941bcf0000cd22527 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class Bullet : MonoBehaviour
{
float force = 1.0f;
float currentTime = 0.0f;
float sleeptime = 1.0f;
public void Initialize(Transform transform)
{
gameObject.SetActive(true);
currentTime = 0.0f;
this.transform.position = transform.position;
gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
gameObject.GetComponent<Rigidbody>().AddForce(transform.forward * force);
}
public void Update()
{
if (currentTime >= sleeptime)
{
Sleep();
}
currentTime += Time.deltaTime;
}
public void Sleep()
{
gameObject.SetActive(false);
}
}
using UnityEngine;
public class Gun : MonoBehaviour
{
//PoolGeneratorをつけた空のオブジェクト
[SerializeField]
PoolGenerator poolGenerator;
void Update()
{
if (Input.GetKeyDown(KeyCode.Z))
{
GameObject bullet = poolGenerator.GetInactiveObject();
bullet.GetComponent<Bullet>().Initialize(transform);
}
}
}
using System.Collections.Generic;
using UnityEngine;
//空のオブジェクトにつけておく
public class PoolGenerator : MonoBehaviour
{
//Poolしたいオブジェクト
[SerializeField]
GameObject prefab;
//生成したい数
[SerializeField]
int num;
List<Bullet> list = new List<Bullet>();
void Start()
{
Bullet obj;
for (int i = 0; i < num; i++)
{
obj = Instantiate(prefab).GetComponent<Bullet>();
obj.transform.parent = transform;
obj.gameObject.SetActive(false);
list.Add(obj);
}
}
public GameObject GetInactiveObject()
{
for (int i = 0; i < list.Count; i++)
{
if (!list[i].gameObject.activeSelf)
{
return list[i].gameObject;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment