Created
October 17, 2018 17:24
-
-
Save Makizemi/c059e1c69a30102941bcf0000cd22527 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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