Im trying to rotate a gameobject through an array of Quaternions that I've read in via a CSV file. Its currently not rotating the objectas i believe i'm not updating the transform.rotation correctly. Any help resolving this would be greatly appreciated, let me know if you need anymore information.
RotationAnimator.cs The Rotator Script:
public class RotationAnimator : MonoBehaviour
{
public Transform playbackTarget;
[HideInInspector]
public bool playingBack = false;
public CSVReader csvReader;
public void PlayRecording()
{
// -1 as it reads the last blank line of the CSV for reasons
for (int row = 0; row < csvReader.quaternionRecords.Length-1; row++)
{
playbackTarget.rotation = new Quaternion(csvReader.quaternionRecords[row].x, csvReader.quaternionRecords[row].y, csvReader.quaternionRecords[row].z, csvReader.quaternionRecords[row].w);
}
}
}
CSVReader.cs The script reading the csv file
public class CSVReader : MonoBehaviour
{
public QuaternionRecord[] quaternionRecords;
public List<List<String>> fileData;
ILogging logger;
string path = "Assets\\Logs\\RotationList.csv";
private void OnEnable()
{
logger = Logging.GetCurrentClassLogger();
}
public void ReadFile()
{
var r = File.OpenText(path);
fileData = r.ReadToEnd().Split('\n').Select(s => s.Split(',').ToList()).ToList();
quaternionRecords = new QuaternionRecord[fileData.Count];
// skip last empty line at "file data.count -1"
for(int row = 0; row < fileData.Count-1; row++)
{
try
{
quaternionRecords[row] = new QuaternionRecord();
quaternionRecords[row].time = float.Parse(fileData[row][0]);
quaternionRecords[row].x = float.Parse(fileData[row][1]);
quaternionRecords[row].y = float.Parse(fileData[row][2]);
quaternionRecords[row].z = float.Parse(fileData[row][3]);
quaternionRecords[row].w = float.Parse(fileData[row][4]);
}
catch(Exception e)
{
Debug.Log("Ouch!");
}
}
r.Close();
}
public struct QuaternionRecord
{
public float time;
public float x;
public float y;
public float z;
public float w;
}
}
Where PlayRecording is called:
public void Playback()
{
Debug.Log("Beginning Playback...");
csvReader.ReadFile();
rotationAnimator.PlayRecording();
}
Here is a way to itterate the quaternionRecords using Coroutines by modifying your existing code.
//Change void to IEnumerator
public IEnumerator PlayRecording()
{
for (int row = 0; row < csvReader.quaternionRecords.Length; row++)
{
playbackTarget.rotation = new Quaternion(csvReader.quaternionRecords[row].x, csvReader.quaternionRecords[row].y, csvReader.quaternionRecords[row].z, csvReader.quaternionRecords[row].w);
//Add this line to wait 1 second until next itteration
yield return new WaitForSeconds(1f);
}
}
public void Playback()
{
Debug.Log("Beginning Playback...");
csvReader.ReadFile();
//Change to StartCourotine
StartCoroutine(rotationAnimator.PlayRecording());
}
I haven't tested the code so it might not work and it might not be the best solution but it is a a way to do it. Other ways is using Update with Time.deltaTime
Related
I am developing a Tower Defence game and I need a wave spawner. I tried to use Brackeys Wave spawner but it only supports one type of enemy per wave and I tried to make one myself like this:
[System.Serializable]
public class WaveContent
{
public Transform enemy;
public int count;
}
[System.Serializable]
public class Wave
{
public string Name;
public WaveContent[] Enemy;
public float Rate = 5f;
}
instead of this:
[System.Serializable]
public class Wave
{
public string name;
public Transform enemy;
public int count;
public float rate;
}
This is the code from the 40min Brackeys video
using UnityEngine;
using System.Collections;
public class WaveSpawner : MonoBehaviour {
public enum SpawnState { SPAWNING, WAITING, COUNTING };
[System.Serializable]
public class Wave
{
public string name;
public Transform enemy;
public int count;
public float rate;
}
public Wave[] waves;
private int nextWave = 0;
public int NextWave
{
get { return nextWave + 1; }
}
public Transform[] spawnPoints;
public float timeBetweenWaves = 5f;
private float waveCountdown;
public float WaveCountdown
{
get { return waveCountdown; }
}
private float searchCountdown = 1f;
private SpawnState state = SpawnState.COUNTING;
public SpawnState State
{
get { return state; }
}
void Start()
{
if (spawnPoints.Length == 0)
{
Debug.LogError("No spawn points referenced.");
}
waveCountdown = timeBetweenWaves;
}
void Update()
{
if (state == SpawnState.WAITING)
{
state = SpawnState.COUNTING;
/*if (!EnemyIsAlive())
{
WaveCompleted();
}
else
{
return;
}*/
}
if (waveCountdown <= 0)
{
if (state != SpawnState.SPAWNING)
{
StartCoroutine( SpawnWave ( waves[nextWave] ) );
}
}
else
{
waveCountdown -= Time.deltaTime;
}
}
void WaveCompleted()
{
Debug.Log("Wave Completed!");
state = SpawnState.COUNTING;
waveCountdown = timeBetweenWaves;
if (nextWave + 1 > waves.Length - 1)
{
nextWave = 0;
Debug.Log("ALL WAVES COMPLETE! Looping...");
}
else
{
nextWave++;
}
}
bool EnemyIsAlive()
{
searchCountdown -= Time.deltaTime;
if (searchCountdown <= 0f)
{
searchCountdown = 1f;
if (GameObject.FindGameObjectWithTag("Enemy") == null)
{
return false;
}
}
return true;
}
IEnumerator SpawnWave(Wave _wave)
{
Debug.Log("Spawning Wave: " + _wave.name);
state = SpawnState.SPAWNING;
for (int i = 0; i < _wave.count; i++)
{
SpawnEnemy(_wave.enemy);
yield return new WaitForSeconds( 1f/_wave.rate );
}
state = SpawnState.WAITING;
yield break;
}
void SpawnEnemy(Transform _enemy)
{
Debug.Log("Spawning Enemy: " + _enemy.name);
Transform _sp = spawnPoints[ Random.Range (0, spawnPoints.Length) ];
Instantiate(_enemy, _sp.position, _sp.rotation);
}
}
And I need to add this to the code to get what I am expecting
[System.Serializable]
public class WaveContent
{
public Transform enemy;
public int count;
}
[System.Serializable]
public class Wave
{
public string Name;
public WaveContent[] Enemy;
public float Rate = 5f;
}
But I was not able to, can anyone help me?
Thanks in advance,
Dev
You should look at his code, there will be those lines of code :
IEnumerator SpawnWave(Wave _wave)
{
state = SpawnState.SPAWNING;
for (int i = 0; i < wave.count; i++)
{
SpawnEnemy(_wave.enemy);
yield return new WaitForSeconds( 1f/_wave.rate );
}
state = SpawnState.WAITING;
yield break;
}
And also those lines of code :
void SpawnEnemy(Transform _enemy)
{
Debug.Log("Spawning Enemy: " + _enemy.name);
Transform sp = spawnPoints[ Randon.Range(0, spawnPoints.Length) ];
Instantiate(_enemy, _sp.position, _sp.rotation);
}
So what is the problem, the problem is that the SpawnEnemy() method is using only one type of enemies each wave, using _enemy from class Wave which is in [System.Serializable], so my idea is that we will make another class Wave, same same as his code :
[System.Serializable]
public class Wave
{
public string name;
public Transform[] enemies;
public int count;
public float rate;
}
And change a little bit in SpawnEnemy() method, which I will add Random.Rage() to choose a different transform ( or we can say enemy )
void SpawnEnemy(Transform[] _enemies)
{
Debug.Log("Spawning Enemy: " + _enemy.name);
int randomIndex = Random.Range(0, _enemies.Count());
Transform sp = spawnPoints[ Randon.Range(0, spawnPoints.Length) ];
Instantiate(_enemies[randomIndex], _sp.position, _sp.rotation);
}
If having any trouble when doing, just comment below, yeah
After reading through the existing comments, I think you really only need one additional edit within the SpawnWave code to achieve what you are looking for - Add a foreach loop to loop through each Wave Contents object and spawn the appropriate number and type of enemy
Given your updated objects, with one update to a field name for clarity
[System.Serializable]
public class WaveContent
{
public Transform enemy;
public int count;
}
[System.Serializable]
public class Wave
{
public string Name;
public WaveContent[] WaveContents;
public float Rate = 5f;
}
Then you just need to loop through the array of WaveContent and call SpawnEnemy for each one, using the WaveContent.Count for the inner loop.
IEnumerator SpawnWave(Wave _wave)
{
Debug.Log("Spawning Wave: " + _wave.name);
state = SpawnState.SPAWNING;
// Loop through your Wave Contents
foreach (var waveContent in Wave.WaveContents)
{
// Spawn the number and type of enemy for each content object
for (int i = 0; i < waveContent.count; i++)
{
SpawnEnemy(waveContent.enemy);
yield return new WaitForSeconds(1f / _wave.rate);
}
}
state = SpawnState.WAITING;
yield break;
}
The Tag script has been working for me so far as an alternate to the unity tags up to this point, allowing me to assign multiple tags to an object at once. Now I want to create a method that will get all of the objects in the scene, filter them by the tag, and then return it as an array. The null reference exception refers to line 41 of the Tag.cs script. How do I fix this?
Tags.cs file
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tags : MonoBehaviour
{
public string[] startTags;
private string[] tags;
private void Start()
{
tags = startTags;
}
public bool FindTag(string search)
{
bool results = false;
for (int i = 0; i < tags.Length; i++)
{
if(search == tags[i])
{
results = true;
break;
}
}
return results;
}
//Find objects by custom script tags
//HERE IS WHERE THE METHOD IS CREATED
public static GameObject[] ObjectsByTag(string search)
{
//Get all objects in scene
GameObject[] allObjects = FindObjectsOfType<GameObject>();
GameObject[] storedObjects = new GameObject[allObjects.Length];
GameObject[] finalObjects;
//Filter
int count = 0;
for (int i = 0; i < allObjects.Length; i++)
{
if (allObjects[i].GetComponent<Tags>().FindTag(search)) //line 41
{
storedObjects[count] = allObjects[i];
count++;
}
}
//Assign final length
finalObjects = new GameObject[count];
//Reassign to final array
for (int i = 0; i < count; i++)
{
finalObjects[i] = storedObjects[i];
}
return finalObjects;
}
}
GameController.cs file (How it is being used
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
//SCREEN START
//Get Screen Size
private float sHeight;
private float sWidth;
//Intended Screen Size
readonly float iH = 695f;
readonly float iW = 1540f;
//Convert
private float cH;
private float cW;
public float ConvertedHeight => cH;
public float ConvertedWidth => cW;
//SCREEN END
//MOUSE CAM START
//mousePostion
private float mX;
private float mZ;
public float MouseX => mX;
public float MouseZ => mZ;
//MOUSE CAM END
//EnemySpeedModifier
private float esm;
public float ESM
{
get { return esm; }
set { esm = value; }
}
//GameOver
private bool gameOver = false;
public bool GameOver
{
get { return gameOver; }
set { gameOver = value; }
}
//game speed
public float speed;
/*
//projectile list
private GameObject[] projectiles;
public GameObject[] Projectiles()
{
return projectiles;
}
public void Projectiles(GameObject value)
{
GameObject[] tempArray = projectiles;
tempArray[projectiles.Length] = value;
projectiles = tempArray;
Debug.Log("Projectile Count: " + projectiles.Length);
}
*/
//HERE IS WHERE IT IS USED
public GameObject[] ProjectilesInScene
{
get
{
return Tags.ObjectsByTag("projectile");
}
}
// Start is called before the first frame update
void Start()
{
//CONVERT SCREEN SIZES START
sHeight = Screen.height;
sWidth = Screen.width;
cH = iH / sHeight;
cW = iW / sWidth;
//CONVERT SCREEN SIZES END
}
// Update is called once per frame
void Update()
{
if (gameOver)
{
speed /= 1 + 0.5f * Time.deltaTime;
}
//Update mose position
mX = Input.mousePosition.x;
mZ = Input.mousePosition.y;
}
}
It seems that not all of your GameObject objects have the Tags component. Per the GameObject.GetComponent documentation
Returns the component of Type type if the game object has one attached, null if it doesn't.
If you know that some objects won't have the Tags component, your line 41 can use a simple null conditional operator:
if (allObjects[i].GetComponent<Tags>()?.FindTag(search) == true)
{
...
}
Note the ? after GetComponent<Tags>().
I have been working on a minecraft clone game in Unity 2017.3 and C# and i started all right but when i worked on the super flat world generation system there began a problem. Inside the World mono behaviour, in the Generate void, there are three nested for loops which should generate a new dirt block on every possible position between 0 and 5
But it only makes a line of dirt block stretching along the Z axis.
Here is the code for PlaceableItem(attached to dirtPrefab) and World(attached to World)
Placeable Item class
using UnityEngine;
using System.Collections;
public class PlaceableItem : MonoBehaviour
{
public string nameInInventory = "Unnamed Block";
public int maxStack = 64;
public bool destructible = true;
public bool explodesOnX = false;
public bool abidesGravity = false;
public bool isContainer = false;
public bool canBeSleptOn = false;
public bool dropsSelf = false;
private Rigidbody rb;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (abidesGravity) {
rb.useGravity = true;
} else {
rb.useGravity = false;
}
}
private void OnDestroy()
{
if (dropsSelf) {
//Drop this gameObject
}
}
public void Explode() {
if (!explodesOnX)
return;
}
public void OnMouseDown()
{
if (isContainer && !canBeSleptOn) {
//Open the container inventory
} else if (canBeSleptOn && !isContainer) {
//Make the character sleep on the item
}
}
private void OnMouseOver()
{
if (Input.GetMouseButtonDown(1) && destructible) {
Destroy(gameObject);
}
}
}
World class
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class World : MonoBehaviour {
public GameObject dirtPrefab;
public bool generateAutomatically = true;
// Use this for initialization
void Start () {
if (generateAutomatically) {
Generate();
}
}
// Update is called once per frame
void Update () {
}
void Generate() {
for (int x = 0; x <= 5; x++) {
for (int y = 0; y <= 5; y++) {
for (int z = 0; z <= 5; z++) {
Instantiate(dirtPrefab, new Vector3(x, y, z), Quaternion.identity);
}
}
}
}
void RemoveAllBlocks() {
foreach (PlaceableItem placeableItem in GetComponentsInChildren<PlaceableItem>()) {
Destroy(placeableItem.gameObject);
}
}
}
Thanks in advance, fellow developers!
Hope this is not a stupid question!
[SOLVED] I realised i had a recttransform somehow attached to my dirt prefab. Removing it and adding a transform instead helped.
What I have
Scenario where a sphere moves towards a cube. There are multiple cubes. I want it to go to 1 cube that is within sight, and when it reached the cube, I want it to search for the next one. I know this should be easy but I've tried to fix this for several hours.
Code
WithinSight.cs
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
public class WithinSight : Conditional {
public float fieldOfViewAngle;
public string targetTag;
public SharedTransform target;
private Transform[] possibleTargets;
public override void OnAwake() {
var targets = GameObject.FindGameObjectsWithTag (targetTag);
possibleTargets = new Transform[targets.Length];
for (int i = 0; i < targets.Length; ++i) {
possibleTargets [i] = targets [i].transform;
}
}
public override TaskStatus OnUpdate() {
for (int i = 0; i < possibleTargets.Length; ++i) {
if (withinSight(possibleTargets [i], fieldOfViewAngle)) {
target.Value = possibleTargets [i];
return TaskStatus.Success;
gameObject.tag = "Untagged";
}
}
return TaskStatus.Failure;
}
public bool withinSight(Transform targetTransform, float fieldOfViewAngle) {
Vector3 direction = targetTransform.position - transform.position;
return Vector3.Angle(direction, transform.forward) < fieldOfViewAngle;
}
}
MoveTowards.cs
using UnityEngine;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;
public class MoveTowards : Action {
public float speed = 0;
public SharedTransform target;
private bool pietje;
void PrintMessage (string message) {
Debug.Log(message);
}
void Start() {
pietje = false;
}
public override TaskStatus OnUpdate() {
if (Vector3.SqrMagnitude (transform.position - target.Value.position) < 0.1f && !pietje) {
PrintMessage ("Found the cube.");
pietje = true;
if (pietje) {
PrintMessage ("Searching...");
pietje = false;
}
return TaskStatus.Success;
}
transform.position = Vector3.MoveTowards (transform.position, target.Value.position, speed * Time.deltaTime);
transform.LookAt (target.Value.position);
return TaskStatus.Running;
}
}
Anyone that can help me will get a virtual cookie! (hmmm...)
I think the error is OnUpdate() in WithinSight class. When you do the return it never does this gameObject.tag = "Untagged";
Change the order of the lines like this.
public override TaskStatus OnUpdate() {
for (int i = 0; i < possibleTargets.Length; ++i) {
if (withinSight(possibleTargets [i], fieldOfViewAngle)) {
target.Value = possibleTargets [i];
gameObject.tag = "Untagged";
return TaskStatus.Success;
}
}
return TaskStatus.Failure;
}
I can't reproduce this scenario, but this code won´t go back to a previuos cube. In case you want that you should save a reference of the last cube the sphere moved towards and do the comparisons in OnUpdate() of WithinSight.
I was having trouble converting an object pool script from UnityScript to C#, which I got a lot of good help with here. Now I'm having an issue trying to actually get a game object from the pool. I have three scripts all interacting with one another, so I'm not quite sure where it's going wrong. Here are the two scripts for the object pool, which I believe are all squared away and they're not giving any errors:
public class EasyObjectPool : MonoBehaviour {
[System.Serializable]
public class PoolInfo{
[SerializeField]
public string poolName;
public GameObject prefab;
public int poolSize;
public bool canGrowPoolSize = true;
}
[System.Serializable]
public class Pool{
public List<PoolObject> list = new List<PoolObject>();
public bool canGrowPoolSize;
public void Add (PoolObject poolObject){
list.Add(poolObject);
}
public int Count (){
return list.Count;
}
public PoolObject ObjectAt ( int index ){
PoolObject result = null;
if(index < list.Count) {
result = list[index];
}
return result;
}
}
static public EasyObjectPool instance ;
[SerializeField]
PoolInfo[] poolInfo = null;
private Dictionary<string, Pool> poolDictionary = new Dictionary<string, Pool>();
void Start () {
instance = this;
CheckForDuplicatePoolNames();
CreatePools();
}
private void CheckForDuplicatePoolNames() {
for (int index = 0; index < poolInfo.Length; index++) {
string poolName= poolInfo[index].poolName;
if(poolName.Length == 0) {
Debug.LogError(string.Format("Pool {0} does not have a name!",index));
}
for (int internalIndex = index + 1; internalIndex < poolInfo.Length; internalIndex++) {
if(poolName == poolInfo[internalIndex].poolName) {
Debug.LogError(string.Format("Pool {0} & {1} have the same name. Assign different names.", index, internalIndex));
}
}
}
}
private void CreatePools() {
foreach(PoolInfo currentPoolInfo in poolInfo){
Pool pool = new Pool();
pool.canGrowPoolSize = currentPoolInfo.canGrowPoolSize;
for(int index = 0; index < currentPoolInfo.poolSize; index++) {
//instantiate
GameObject go = Instantiate(currentPoolInfo.prefab) as GameObject;
PoolObject poolObject = go.GetComponent<PoolObject>();
if(poolObject == null) {
Debug.LogError("Prefab must have PoolObject script attached!: " + currentPoolInfo.poolName);
} else {
//set state
poolObject.ReturnToPool();
//add to pool
pool.Add(poolObject);
}
}
Debug.Log("Adding pool for: " + currentPoolInfo.poolName);
poolDictionary[currentPoolInfo.poolName] = pool;
}
}
public PoolObject GetObjectFromPool ( string poolName ){
PoolObject poolObject = null;
if(poolDictionary.ContainsKey(poolName)) {
Pool pool = poolDictionary[poolName];
//get the available object
for (int index = 0; index < pool.Count(); index++) {
PoolObject currentObject = pool.ObjectAt(index);
if(currentObject.AvailableForReuse()) {
//found an available object in pool
poolObject = currentObject;
break;
}
}
if(poolObject == null) {
if(pool.canGrowPoolSize) {
Debug.Log("Increasing pool size by 1: " + poolName);
foreach (PoolInfo currentPoolInfo in poolInfo) {
if(poolName == currentPoolInfo.poolName) {
GameObject go = Instantiate(currentPoolInfo.prefab) as GameObject;
poolObject = go.GetComponent<PoolObject>();
//set state
poolObject.ReturnToPool();
//add to pool
pool.Add(poolObject);
break;
}
}
} else {
Debug.LogWarning("No object available in pool. Consider setting canGrowPoolSize to true.: " + poolName);
}
}
} else {
Debug.LogError("Invalid pool name specified: " + poolName);
}
return poolObject;
}
}
And:
public class PoolObject : MonoBehaviour {
[HideInInspector]
public bool availableForReuse = true;
void Activate () {
availableForReuse = false;
gameObject.SetActive(true);
}
public void ReturnToPool () {
gameObject.SetActive(false);
availableForReuse = true;
}
public bool AvailableForReuse () {
//true when isAvailableForReuse & inactive in hierarchy
return availableForReuse && (gameObject.activeInHierarchy == false);
}
}
The original UnityScript said to retrieve an object from the pool with this statement:
var poolObject : PoolObject = EasyObjectPool.instance.GetObjectFromPool(poolName);
This is how I tried to do that in my shooting script with it trying to fire a bullet prefab from the pool:
public class ShootScript : MonoBehaviour {
public PoolObject poolObject;
private Transform myTransform;
private Transform cameraTransform;
private Vector3 launchPosition = new Vector3();
public float fireRate = 0.2f;
public float nextFire = 0;
// Use this for initialization
void Start () {
myTransform = transform;
cameraTransform = myTransform.FindChild("BulletSpawn");
}
void Update () {
poolObject = EasyObjectPool.instance.GetObjectFromPool<poolName>();
if(Input.GetButton("Fire1") && Time.time > nextFire){
nextFire = Time.time + fireRate;
launchPosition = cameraTransform.TransformPoint(0, 0, 0.2f);
poolObject.Activate();
poolObject.transform.position = launchPosition;
poolObject.transform.rotation = Quaternion.Euler(cameraTransform.eulerAngles.x + 90, myTransform.eulerAngles.y, 0);
}
}
}
My shoot script is giving me two errors:
1. The type or namespace name 'poolName' could not be found. Are you missing a using directive or an assembly reference?
For the line:
poolObject = EasyObjectPool.instance.GetObjectFromPool<poolName>();
2. 'PoolObject.Activate()' is inaccessible due to its protection level
For the line:
poolObject.Activate();
Did I mis-translate the UnityScript or am I missing something else? Any input is greatly appreciated
I think your object pool is incorrectly programmed. When you have a method like CheckForDuplicatePoolNames() ask yourself if you need a different collection like dictionary.
Keep it simple.
I recently implemented one and I have tested. It works pretty well.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class PoolObject{
public GameObject prefab;
public int startNum;
public int allocateNum;
public Transform anchor;
}
public class ObjectPool<T> : MonoBehaviour where T:Component{
public PoolObject[] poolObjects;
public bool ______________;
public Dictionary<string,Queue<T>> pool = new Dictionary<string, Queue<T>> ();
public Dictionary<string, List<T>> spawned = new Dictionary<string, List<T>> ();
public Transform anchor;
public void Init(){
InitPool ();
StartAllocate ();
}
public T Spawn(string type){
if (pool [type].Count == 0) {
int i = FindPrefabPosition(type);
if(poolObjects[i].allocateNum == 0)
return null;
Allocate(poolObjects[i], poolObjects[i].allocateNum);
}
T t = pool [type].Dequeue ();
spawned[type].Add (t);
t.gameObject.SetActive (true);
return t;
}
public void Recycle(T t){
if (spawned [t.name].Remove (t)) {
pool[t.name].Enqueue(t);
t.gameObject.SetActive(false);
}
}
private void Allocate(PoolObject po, int number){
for (int i=0; i<number; i++) {
GameObject go = Instantiate (po.prefab) as GameObject;
go.name = po.prefab.name;
go.transform.parent = po.anchor != null? po.anchor : anchor;
T t = go.GetComponent<T>();
pool[t.name].Enqueue(t);
t.gameObject.SetActive(false);
}
}
private int FindPrefabPosition(string type){
int position = 0;
while (poolObjects[position].prefab.name != type) {
position++;
}
return position;
}
void InitPool(){
if(anchor == null)
anchor = new GameObject("AnchorPool").transform;
for (int i =0; i<poolObjects.Length; i++) {
T t = poolObjects[i].prefab.GetComponent<T>();
t.name = poolObjects[i].prefab.name;
pool[t.name] = new Queue<T>();
spawned[t.name] = new List<T>();
}
}
void StartAllocate(){
for (int i=0; i<poolObjects.Length; i++) {
Allocate(poolObjects[i], poolObjects[i].startNum );
}
}
}
Example:
public class CoinsPool : ObjectPool<CoinScript>{}
In the unity inspector configure the coin prefab, the startNum and the allocateNum.
Somewhere:
void Awake(){
coinsPool = GetComponent<CoinsPool>();
coinsPool.Init();
}
CoinScript cs = coinsPool.Spawn("Coin"); //Coin is the name of the coin prefab.
Later
coinsPool.Recycle(cs);
The thing you write within <> should be a class name like PoolObject if the function is generic, which it is not. So to solve this you simply need to change
poolObject = EasyObjectPool.instance.GetObjectFromPool<poolName>();
to
string poolName = "thePoolNameYouWant";
poolObject = EasyObjectPool.instance.GetObjectFromPool(poolName);
Function are private by default so to solve the "inaccessible due to its protection level" error you need to make the function public by changing this
void Activate () {
availableForReuse = false;
gameObject.SetActive(true);
}
to this
public void Activate () {
availableForReuse = false;
gameObject.SetActive(true);
}