IndexOutOfRangeException: Can't figure out why index out of bound - unity3d

So, I have a list of Upgrade systems for my game but it has a bug on it when I press upgrade for a second time the index out of range then pressed for the third times the index out of range gone. this whole script.
void Start()
{
newSelectedIndex = previousSelectedIndex = PlayerPrefs.GetInt("currentPlayer");
btn = Select_Player[newSelectedIndex].GetComponent<Button>();
btn.interactable = false;
Coins = M_CoinManager.instance.Coins;
for (int i = 0; i < Select_Player.Length; i++)
{
priceText[i].text = Cost_Player[i].ToString();
value_player[i] = "" + i;
Select_Player[i].SetActive(false);
buyPlayer[i] = PlayerPrefs.GetInt(value_player[i]);
}
//if(PlayerPrefs.HasKey("currentPlayer")){
selectedVehicleIndex = PlayerPrefs.GetInt("currentPlayer");
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
// Update is called once per frame
void Update()
{
for (int i = 0; i < Select_Player.Length; i++)
{
buyPlayer[i] = PlayerPrefs.GetInt(value_player[i]);
if (i == buyPlayer[i])
{
Select_Player[i].SetActive(true);
upgradeBtn[i].interactable = true;
UpgradeButtonStatus();
}
else
{
upgradeBtn[i].interactable = false;
}
}
}
public void BuyCharact(int id)
{
M_SoundManager.instance.playUIsfx();
if (Cost_Player[id] <= Coins)
{
M_CoinManager.instance.AddCoins(-Cost_Player[id]);
PlayerPrefs.SetInt(value_player[id], id);
}
else
{
_CoinShake.DoShake();
Debug.Log("Does have enough coin");
}
}
public void Reset()
{
for (int i = 0; i < Select_Player.Length; i++)
{
PlayerPrefs.SetInt(value_player[i], 0);
}
}
public void Select(int id)
{
previousSelectedIndex = newSelectedIndex;
newSelectedIndex = id;
newSelectedIndex = selectedVehicleIndex;
PlayerPrefs.SetInt("currentPlayer", newSelectedIndex);
Button newbtn = Select_Player[previousSelectedIndex].GetComponent<Button>();
btn = Select_Player[newSelectedIndex].GetComponent<Button>();
btn.interactable = false;
newbtn.interactable = true;
M_SoundManager.instance.playUIsfx();
Debug.Log("Selected TypeCar" + newSelectedIndex);
}
public void nextVehicle()
{
M_SoundManager.instance.playUIsfx();
theVehicles[selectedVehicleIndex].SetActive(false);
selectedVehicleIndex = (selectedVehicleIndex + 1) % theVehicles.Length;
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
public void PreviousVehicle()
{
M_SoundManager.instance.playUIsfx();
theVehicles[selectedVehicleIndex].SetActive(false);
selectedVehicleIndex--;
if (selectedVehicleIndex < 0)
{
selectedVehicleIndex += theVehicles.Length;
}
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
public void VehicleInfo()
{
currLevel = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel;
levelText[selectedVehicleIndex].text = "Level: " + (currLevel + 1);
powerText[selectedVehicleIndex].text = "Power: " + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[currLevel].motorPower;
brakeText[selectedVehicleIndex].text = "Brake: " + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[currLevel].brakePower;
Debug.Log(selectedVehicleIndex);
}
public void upgradeMethod()
{
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
if (Coins >= _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex].unlockCost)
{
Coins -= _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex].unlockCost;
_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel++;
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
VehicleInfo();
}
}
private void UpgradeButtonStatus()
{
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtn[selectedVehicleIndex].interactable = true;
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
}
and the error reference to this method :
private void UpgradeButtonStatus()
{
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtn[selectedVehicleIndex].interactable = true;
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
}
as you can see on the update that's what I mean. after i press upgrade for third times the error stopped.
and this for the inpector

Arrays length is one higher than their highest index, but last iteration of "for" loops goes to array.length.
You need to make "for" loops to array.length-1.
I see you do "for" loops of up to array.length.
I haven't truly read thru your whole script so there might be more, but it's a typical error in my "for" loops so I think that is causing your error.

Related

Unity Destroy() doesn't delete script

Noob mistake I was only referencing the parents brain from the child's instead of copying it directly. It's a neural network that can grow in size (or shrink) through genetics. I was going to post it but it doesn't fit on this without me having to type a larger ratio of words to code oh look it works now
public class Animal1 : MonoBehaviour
{
public class Neuron1
{
public int[] children;
public float[] weights;
public float bias;
public float value;
public Neuron1()
{
children = new int[10];
for (int i = 0; i < 10; i++)
{
children[i] = -1;
}
weights = new float[10];
for (int i = 0; i < 10; i++)
{
weights[i] = 1;
}
bias = 0;
value = 0;
}
}
float sightRange = 2;
Vector2 left = new Vector2(-.4f,.6f);
Vector2 right = new Vector2(.4f, .6f);
RaycastHit2D hitLeft;
RaycastHit2D hitForward;
RaycastHit2D hitRight;
public LayerMask animalLayerMask;
[System.NonSerialized]
public int food = 0;
int foodCounter = 0;
int foodForReproduction = 3;
float noFoodCounter = 0;
int lifeWithoutFood = 20;
int maxBrainSize = 100;
[System.NonSerialized]
public Neuron1[] brain1 = new Neuron1[100]; //first three and last three are inputs and outputs and are never mutated
int childrenMaxAmount = 5;
float biasInitRange = 2;
float weightInitRange = 2;
int outputSize = 2;
int inputSize = 3;
GameObject manager;
[System.NonSerialized]
public bool firstGen = false;
[System.NonSerialized]
public GameObject parent1;
[System.NonSerialized]
public bool directCopy = false;
float maxTravelRange = 5;
Color color;
float colorMutationRate = .1f;
public GameObject animal1Prefab1;
bool debugBool = false;
void Start()
{
manager = GameObject.Find("Manager Object");
if (firstGen == true)
{
InitializeBrain(3, 2, 20);
firstGen = false;
transform.GetComponent<SpriteRenderer>().color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), 1);
}
else
{
if (parent1.GetComponent<Animal1>().brain1[0].bias == 1234)
{
Debug.Log("parent passing brain after deletion");
}
Mutate(parent1, 5, 1f, .5f);
transform.GetComponent<SpriteRenderer>().color = color;
}
}
void Update()
{
if (brain1[0].bias == 1234)
{
GetComponent<SpriteRenderer>().color = Color.black;
}
//teleportation
if (transform.position.x > maxTravelRange)
{
Vector2 newPosition = new Vector2(-maxTravelRange, transform.position.y);
transform.position = newPosition;
}
if (transform.position.x < -maxTravelRange)
{
Vector2 newPosition = new Vector2(maxTravelRange, transform.position.y);
transform.position = newPosition;
}
if (transform.position.y > maxTravelRange)
{
Vector2 newPosition = new Vector2(transform.position.x, -maxTravelRange);
transform.position = newPosition;
}
if (transform.position.y < -maxTravelRange)
{
Vector2 newPosition = new Vector2(transform.position.x, maxTravelRange);
transform.position = newPosition;
}
//input
hitLeft = Physics2D.Raycast(transform.position, transform.TransformDirection(left), sightRange, ~animalLayerMask); //left
hitForward = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), sightRange, ~animalLayerMask); //forward
hitRight = Physics2D.Raycast(transform.position, transform.TransformDirection(right), sightRange, ~animalLayerMask); //right
if (hitLeft)
{
brain1[0].value = 1;
}
if (hitForward)
{
brain1[1].value = 1;
}
if (hitRight)
{
brain1[2].value = 1;
}
//output
Think();
// one output for speed, another for turning
int rotDir = 1;
if (brain1[maxBrainSize - 1].value < 0)
{
rotDir = -1;
}
Vector3 eulerRotation = new Vector3(0, 0, (45 * rotDir + (transform.rotation.eulerAngles.z % 360)) % 360);
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(eulerRotation), Mathf.Abs(brain1[maxBrainSize - 1].value) * 25 * Time.deltaTime);
if (brain1[maxBrainSize - 2].value > 0) // so they can't go backwards
{
transform.Translate(Vector2.up * (brain1[maxBrainSize - 2].value * .1f) * Time.deltaTime);
}
//reset outputs
brain1[maxBrainSize - 2].value = 0;
brain1[maxBrainSize - 1].value = 0;
// reset inputs
brain1[0].value = 0;
brain1[1].value = 0;
brain1[2].value = 0;
noFoodCounter += Time.deltaTime;
if (food > 0)
{
foodCounter++;
food = 0;
noFoodCounter = 0;
}
if (foodCounter > foodForReproduction)
{
foodCounter = 0;
Reproduce();
}
if (noFoodCounter > lifeWithoutFood/2)
{
foodCounter = 0;
}
if (noFoodCounter > lifeWithoutFood)
{
Destroy(gameObject);
}
}
void InitializeBrain(int inputs, int outputs, int sizeExcludingInputsAndOutputs)
{
for (int i = 0; i < sizeExcludingInputsAndOutputs + inputs; i++)
{
brain1[i] = new Neuron1();
}
for (int i = maxBrainSize - outputs; i < maxBrainSize; i++) // outputs
{
brain1[i] = new Neuron1();
}
// all neurons in between the inputs and outputs
for (int i = inputs; i < sizeExcludingInputsAndOutputs + inputs; i++)
{
brain1[i].bias = Random.Range(-biasInitRange, biasInitRange);
for (short j = 0; j < childrenMaxAmount -1; j++) // -1 so there is always at least one free space for a child
{
int rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains) // making sure none are children of themselves, and that it doesn't already have this child
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[i].children[h] == rnd1) // if it already has this child
{
alreadyContains = true;
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
while (rnd1 == i) // and its not itself
{
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
}
break;
}
}
errorCounter++;
if (errorCounter > 100) // so we don't get stuck in small network sizes
{
goto outside2;
}
}
brain1[i].children[j] = rnd1;
brain1[i].weights[j] = Random.Range(-weightInitRange, weightInitRange);
if (Random.Range(1, 10) > 8)
{
break; // so not every neuron has the same amount of children
}
}
outside2:
{
}
}
// assign children of inputs
for (int i = 0; i < inputs; i++)
{
for (int j = 0; j < childrenMaxAmount; j++) // assigning all max children (sometimes) to inputs, their amounts of children will never change
{
int rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains)
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[i].children[h] == rnd1)
{
alreadyContains = true;
rnd1 = Random.Range(inputs, sizeExcludingInputsAndOutputs + inputs);
}
}
errorCounter++;
if (errorCounter > 1000) // so we don't get stuck in small network sizes
{
goto outside1;
}
}
brain1[i].children[j] = rnd1;
//brain1[i].weights[j] = 100; // input weight
}
outside1:
{
}
}
RemoveDeadNeurons();
// assign parents of outputs
int brainEnd = maxBrainSize - outputs;
for (int i = brainEnd; i < maxBrainSize; i++)
{
for (short j = 0; j < childrenMaxAmount; j++) // same amount of parents as inputs have children
{
int rnd1 = Random.Range(inputs, brainEnd);
while (brain1[rnd1] == null)
{
rnd1 = Random.Range(inputs, brainEnd);
}
bool alreadyContains = true;
int errorCounter = 0;
while (alreadyContains) //making sure we dont already have this parent
{
alreadyContains = false;
for (short h = 0; h < childrenMaxAmount; h++)
{
if (brain1[rnd1].children[h] == i)
{
alreadyContains = true;
rnd1 = Random.Range(inputs, brainEnd);
while (brain1[rnd1] == null)
{
rnd1 = Random.Range(inputs, brainEnd);
}
}
}
errorCounter++;
if (errorCounter > 1000) // so we don't get stuck
{
goto outside3;
}
}
for (int h = 0; h < childrenMaxAmount; h++) //adding to next available child space of the parent
{
if (brain1[rnd1].children[h] == -1)
{
brain1[rnd1].children[h] = i;
brain1[rnd1].weights[h] = Random.Range(-weightInitRange, weightInitRange);
break;
}
}
}
outside3:
{
}
}
}
void Think()
{
int[] activatedChildrenIndexes = new int[500];
int[] workingArray = new int[500];
int workingArrayCounter = 0;
short layerCounter = 0;
for (int i = 0; i < 500; i++)
{
activatedChildrenIndexes[i] = -1;
}
//initializing inputs as first activated children layer to be calculated
activatedChildrenIndexes[0] = 0;
activatedChildrenIndexes[1] = 1;
activatedChildrenIndexes[2] = 2;
int thoughtDepth = 6; //keep this as low as possible, will change to make it a percent of the amount of neurons that already exist
for (int x = 0; x < thoughtDepth; x++)
{
for (int i = 0; i < 500; i++) // cycle through activated children and add their activated children to a list
{
int currentNodeIndex = activatedChildrenIndexes[i];
if (currentNodeIndex == -1)
{
layerCounter++;
break;
}
//activation function
if (brain1[currentNodeIndex].value <= 0)
{
brain1[currentNodeIndex].value = 0;
}
else
{
brain1[currentNodeIndex].value = 1;
}
for (int j = 0; j < childrenMaxAmount; j++)
{
if (brain1[currentNodeIndex].children[j] == -1)
{
break;
}
brain1[brain1[currentNodeIndex].children[j]].value
+= (brain1[currentNodeIndex].value * brain1[currentNodeIndex].weights[j]) + brain1[currentNodeIndex].bias;
bool activatedChildIsInNextLayer = false;
for (int h = 0; h < 500; h++)
{
if (brain1[currentNodeIndex].children[j] == activatedChildrenIndexes[h])
{
activatedChildIsInNextLayer = true;
}
}
if (brain1[brain1[currentNodeIndex].children[j]].value > 0
|| layerCounter == 0
|| brain1[currentNodeIndex].children[j] > maxBrainSize - outputSize)
{
if (!activatedChildIsInNextLayer)
{
workingArray[workingArrayCounter] = brain1[currentNodeIndex].children[j];
if (workingArrayCounter < 499)//to prevent out of bounds indexing
{
workingArrayCounter++;
}
}
}
if (brain1[brain1[currentNodeIndex].children[j]].value < 0 && brain1[currentNodeIndex].children[j] < maxBrainSize - outputSize)
{
brain1[brain1[currentNodeIndex].children[j]].value = 0; //resetting negative nodes that didn't get added to next layer
}
}
brain1[currentNodeIndex].value = 0; // resetting value after passing to children
}
for (int i = workingArrayCounter; i < 500; i++)
{
workingArray[i] = -1;
}
workingArrayCounter = 0;
for (int i = 0; i < 500; i++)
{
activatedChildrenIndexes[i] = workingArray[i];
}
}
}
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
for (int i = 0; i < maxBrainSize; i++) // initialized to its parent's brain
{
if (parent.GetComponent<Animal1>().brain1[i] != null)
{
brain1[i] = new Neuron1();
brain1[i].bias = parent.GetComponent<Animal1>().brain1[i].bias;
for (int j = 0; j < childrenMaxAmount; j++)
{
brain1[i].children[j] = parent.GetComponent<Animal1>().brain1[i].children[j];
brain1[i].weights[j] = parent.GetComponent<Animal1>().brain1[i].weights[j];
}
}
}
for (int i = inputSize; i < maxBrainSize - outputSize; i++)
{
if (brain1[i] != null)
{
if (Random.Range(0, 100) < mutationRate) // it will be mutated
{
switch (Random.Range(1, 5))
{
case 1: //change one of its weights
int weightCounter = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its weights
{
if (brain1[i].children[k] != -1)
{
weightCounter++;
}
else
{
break;
}
}
brain1[i].weights[Random.Range(0, weightCounter)] += Random.Range(-weightsMutate, weightsMutate);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 2: //change its bias
brain1[i].bias += Random.Range(-biasMutate, biasMutate);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 3: //break a connection/ remove neuron
int childrenCounter = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[i].children[k] != -1)
{
childrenCounter++;
}
else
{
break;
}
}
int rndChild = Random.Range(0, childrenCounter);
for (int s = rndChild; s < childrenMaxAmount - 1; s++) // shift children list down starting from rndChild and to the second to last element
{
brain1[i].children[s] = brain1[i].children[s + 1];
brain1[i].weights[s] = brain1[i].weights[s + 1];
}
brain1[i].children[childrenMaxAmount - 1] = -1; // removing the last child after shifting the list down one
brain1[i].weights[childrenMaxAmount - 1] = 0;
RemoveDeadNeurons();
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
case 4: //add a new child if possible
int childrenCounter2 = 0;
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[i].children[k] != -1)
{
childrenCounter2++;
}
else
{
break;
}
}
if (childrenCounter2 < childrenMaxAmount) // if we have room for another child
{
int newChild = Random.Range(inputSize, maxBrainSize);
while (brain1[newChild] == null)
{
newChild = Random.Range(inputSize, maxBrainSize);
}
brain1[i].children[childrenCounter2] = newChild;
brain1[i].weights[childrenCounter2] = Random.Range(-weightInitRange, weightInitRange);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
}
break;
}
}
}
}
if (Random.Range(0, 100) < 10) // create a new neuron if space is available for one
{
for (int i = inputSize; i < maxBrainSize - outputSize; i++)
{
if (brain1[i] == null) // the first available neuron
{
brain1[i] = new Neuron1();
int rndParent = Random.Range(0, maxBrainSize - outputSize);
int childrenCounter3 = 0;
if (brain1[rndParent] != null)
{
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[rndParent].children[k] != -1)
{
childrenCounter3++;
}
else
{
break;
}
}
}
while (brain1[rndParent] == null || childrenCounter3 == childrenMaxAmount) // making sure it is both an existing neuron and that it has room for another child
{
childrenCounter3 = 0;
rndParent = Random.Range(0, maxBrainSize - outputSize);
if (brain1[rndParent] != null)
{
for (int k = 0; k < childrenMaxAmount; k++) // counting its children
{
if (brain1[rndParent].children[k] != -1)
{
childrenCounter3++;
}
else
{
break;
}
}
}
}
brain1[rndParent].children[childrenCounter3] = i; //giving the neuron a parent
brain1[rndParent].weights[childrenCounter3] = Random.Range(-weightInitRange, weightInitRange);
int rndChild = Random.Range(inputSize, maxBrainSize);
while(brain1[rndChild] == null)
{
rndChild = Random.Range(inputSize, maxBrainSize);
}
brain1[i].children[0] = rndChild; // giving the new neuron a child, a weight, and its bias
brain1[i].weights[0] = Random.Range(-weightInitRange, weightInitRange);
brain1[i].bias = Random.Range(-biasInitRange, biasInitRange);
color.r += Random.Range(-colorMutationRate, colorMutationRate);
color.g += Random.Range(-colorMutationRate, colorMutationRate);
color.b += Random.Range(-colorMutationRate, colorMutationRate);
break;
}
}
}
}
void RemoveDeadNeurons()
{
bool allGood = false;
while (!allGood)
{
for (int i = inputSize; i < maxBrainSize - outputSize; i++) // for every hidden layer neuron
{
if (brain1[i] != null) // if it's a neuron
{
if (brain1[i].children[0] == -1) // if it has no children
{
brain1[i] = null; // deleting neuron
for (int h = 0; h < maxBrainSize - outputSize; h++) //remove from other neurons children list, including from the input layer
{
if (brain1[h] != null)
{
for (int g = 0; g < childrenMaxAmount; g++)
{
if (brain1[h].children[g] == i) // if brain[h] has the removed neuron as a child
{
for (int s = g; s < childrenMaxAmount - 1; s++) // shift children list down
{
brain1[h].children[s] = brain1[h].children[s + 1];
brain1[h].weights[s] = brain1[h].weights[s + 1];
}
brain1[h].children[childrenMaxAmount - 1] = -1; // removing the last child in the list after shifting it down one
brain1[h].weights[childrenMaxAmount - 1] = 0;
}
}
}
}
goto outsideRDNLoop; // break out of for loop and recheck the brain
}
bool parentless = true;
for (int h = 0; h < maxBrainSize - outputSize; h++) // check if it is parentless
{
if (brain1[h] != null)
{
for (int g = 0; g < childrenMaxAmount; g++)
{
if (brain1[h].children[g] == i) // if it is a child of brain[h]
{
parentless = false;
}
}
}
}
if (parentless)
{
brain1[i] = null; //deleting neuron
goto outsideRDNLoop;
}
}
if (i == (maxBrainSize - outputSize) - 1) // if we reached the end of the for loop and this line, we know the brain was allGood
{
allGood = true;
}
}
outsideRDNLoop:
{
}
}
}
void Reproduce()
{
GameObject offspring = Instantiate(animal1Prefab1, new Vector2(transform.position.x + 1, transform.position.y + 1), Quaternion.identity);
offspring.GetComponent<Animal1>().parent1 = gameObject;
offspring.name = "animal1";
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(transform.position, transform.TransformDirection(left) * sightRange);
Gizmos.DrawRay(transform.position, transform.TransformDirection(Vector2.up) * sightRange);
Gizmos.DrawRay(transform.position, transform.TransformDirection(right) * sightRange);
}
}
I've not run your code, just looked at it, but this looks suspicious if you are having problems with the contents of brain1 being overwritten elsewhere:
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
// This line here is suspicious:
brain1 = parent.GetComponent<Animal1>().brain1; // initialized to its parent's brain
What you are doing here is replacing the reference to the child's brain with the parent's - so if you are starting with just one parent initially, every single entity will be sharing the same brain.
I think perhaps you meant to deep copy the contents from parent's brain into the child's brain? What your assignment here is doing is just taking the reference to the parent's brain and using it as the child brain as well.
Example Deep copy:
Updated Neuron1 class:
public class Neuron1
{
public int[] children;
public float[] weights;
public float bias;
public float value;
public Neuron1()
{
children = new int[10];
for (int i = 0; i < 10; i++)
{
children[i] = -1; // to stop looping when reaching -1
}
weights = new float[10];
for (int i = 0; i < 10; i++)
{
weights[i] = 1;
}
bias = 0;
value = 0;
}
// Added clone function:
public Neuron1 Clone()
{
Neuron1 clone = new Neuron1();
for (int i = 0; i < clone.children.Length; i++)
{
clone.children[i] = this.children[i];
}
for (int i = 0; i < clone.weights.Length; i++)
{
clone.weights[i] = this.weights[i];
}
clone.bias = this.bias;
clone.value = this.value;
return clone;
}
}
Updated start of Mutate function.
void Mutate(GameObject parent, float mutationRate, float weightsMutate, float biasMutate)
{
color = parent.GetComponent<SpriteRenderer>().color;
Neuron1[] parentBrain = parent.GetComponent<Animal1>().brain1; // initialized to its parent's brain
for (int i = 0; i < brain1.Length; ++i)
{
brain1[i] = parentBrain[i].Clone();
}
Well, I have a demo scene here. In it I created an empty game object. It has a script attached to it (CSharp.cs), like this:
In my Update method I wrote
And as soon as I start the game, the game object including the script is deleted.
But if I replace transform.gameObject wit just this then only the script disappears and the game object remains.
DestoryImmediate() is not recommended to be used, instead use Destory()
Destroy() will set the object to null at the end of the frame and whereas DestroyImmediate() function immediately set object reference to null.
DestoryImmediate can also delete prefabs/scenes/art in your project outside of playmode which is another reason you should not use it.

2D procedural dungeon generation game

I am currently messing around with a procedural 2D game in unity. Below are the scripts i am using to generate the dungeon and wanted to know if there was anyway of specifying a standard starting room. I have prefab room built but would like to have a single prefab room players always start in.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class DungeonGeneration : MonoBehaviour {
[SerializeField]
private int numberOfRooms;
[SerializeField]
private int numberOfObstacles;
[SerializeField]
private Vector2Int[] possibleObstacleSizes;
[SerializeField]
private int numberOfEnemies;
[SerializeField]
private GameObject[] possibleEnemies;
[SerializeField]
private GameObject goalPrefab;
[SerializeField]
private TileBase obstacleTile;
private Room[,] rooms;
private Room currentRoom;
private static DungeonGeneration instance = null;
void Awake () {
if (instance == null) {
DontDestroyOnLoad (this.gameObject);
instance = this;
this.currentRoom = GenerateDungeon ();
} else {
string roomPrefabName = instance.currentRoom.PrefabName ();
GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
Tilemap tilemap = roomObject.GetComponentInChildren<Tilemap> ();
instance.currentRoom.AddPopulationToTilemap (tilemap, instance.obstacleTile);
Destroy (this.gameObject);
}
}
void Start () {
string roomPrefabName = this.currentRoom.PrefabName ();
GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
Tilemap tilemap = roomObject.GetComponentInChildren<Tilemap> ();
this.currentRoom.AddPopulationToTilemap (tilemap, this.obstacleTile);
}
private Room GenerateDungeon() {
int gridSize = 3 * numberOfRooms;
rooms = new Room[gridSize, gridSize];
Vector2Int initialRoomCoordinate = new Vector2Int ((gridSize / 2) - 1, (gridSize / 2) - 1);
Queue<Room> roomsToCreate = new Queue<Room> ();
roomsToCreate.Enqueue (new Room(initialRoomCoordinate.x, initialRoomCoordinate.y));
List<Room> createdRooms = new List<Room> ();
while (roomsToCreate.Count > 0 && createdRooms.Count < numberOfRooms) {
Room currentRoom = roomsToCreate.Dequeue ();
this.rooms [currentRoom.roomCoordinate.x, currentRoom.roomCoordinate.y] = currentRoom;
createdRooms.Add (currentRoom);
AddNeighbors (currentRoom, roomsToCreate);
}
int maximumDistanceToInitialRoom = 0;
Room finalRoom = null;
foreach (Room room in createdRooms) {
List<Vector2Int> neighborCoordinates = room.NeighborCoordinates ();
foreach (Vector2Int coordinate in neighborCoordinates) {
Room neighbor = this.rooms [coordinate.x, coordinate.y];
if (neighbor != null) {
room.Connect (neighbor);
}
}
room.PopulateObstacles (this.numberOfObstacles, this.possibleObstacleSizes);
room.PopulatePrefabs (this.numberOfEnemies, this.possibleEnemies);
int distanceToInitialRoom = Mathf.Abs (room.roomCoordinate.x - initialRoomCoordinate.x) + Mathf.Abs(room.roomCoordinate.y - initialRoomCoordinate.y);
if (distanceToInitialRoom > maximumDistanceToInitialRoom) {
maximumDistanceToInitialRoom = distanceToInitialRoom;
finalRoom = room;
}
}
GameObject[] goalPrefabs = { this.goalPrefab };
finalRoom.PopulatePrefabs(1, goalPrefabs);
return this.rooms [initialRoomCoordinate.x, initialRoomCoordinate.y];
}
private void AddNeighbors(Room currentRoom, Queue<Room> roomsToCreate) {
List<Vector2Int> neighborCoordinates = currentRoom.NeighborCoordinates ();
List<Vector2Int> availableNeighbors = new List<Vector2Int> ();
foreach (Vector2Int coordinate in neighborCoordinates) {
if (this.rooms[coordinate.x, coordinate.y] == null) {
availableNeighbors.Add (coordinate);
}
}
int numberOfNeighbors = (int)Random.Range (1, availableNeighbors.Count);
for (int neighborIndex = 0; neighborIndex < numberOfNeighbors; neighborIndex++) {
float randomNumber = Random.value;
float roomFrac = 1f / (float)availableNeighbors.Count;
Vector2Int chosenNeighbor = new Vector2Int(0, 0);
foreach (Vector2Int coordinate in availableNeighbors) {
if (randomNumber < roomFrac) {
chosenNeighbor = coordinate;
break;
} else {
roomFrac += 1f / (float)availableNeighbors.Count;
}
}
roomsToCreate.Enqueue (new Room(chosenNeighbor));
availableNeighbors.Remove (chosenNeighbor);
}
}
private void PrintGrid() {
for (int rowIndex = 0; rowIndex < this.rooms.GetLength (1); rowIndex++) {
string row = "";
for (int columnIndex = 0; columnIndex < this.rooms.GetLength (0); columnIndex++) {
if (this.rooms [columnIndex, rowIndex] == null) {
row += "X";
} else {
row += "R";
}
}
Debug.Log (row);
}
}
public void MoveToRoom(Room room) {
this.currentRoom = room;
}
public Room CurrentRoom() {
return this.currentRoom;
}
public void ResetDungeon() {
this.currentRoom = GenerateDungeon ();
}
}
and
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class Room
{
public Vector2Int roomCoordinate;
public Dictionary<string, Room> neighbors;
private string[,] population;
private Dictionary<string, GameObject> name2Prefab;
public Room (int xCoordinate, int yCoordinate)
{
this.roomCoordinate = new Vector2Int (xCoordinate, yCoordinate);
this.neighbors = new Dictionary<string, Room> ();
this.population = new string[18, 10];
for (int xIndex = 0; xIndex < 18; xIndex += 1) {
for (int yIndex = 0; yIndex < 10; yIndex += 1) {
this.population [xIndex, yIndex] = "";
}
}
this.population [8, 5] = "Player";
this.name2Prefab = new Dictionary<string, GameObject> ();
}
public Room (Vector2Int roomCoordinate)
{
this.roomCoordinate = roomCoordinate;
this.neighbors = new Dictionary<string, Room> ();
this.population = new string[18, 10];
for (int xIndex = 0; xIndex < 18; xIndex += 1) {
for (int yIndex = 0; yIndex < 10; yIndex += 1) {
this.population [xIndex, yIndex] = "";
}
}
this.population [8, 5] = "Player";
this.name2Prefab = new Dictionary<string, GameObject> ();
}
public List<Vector2Int> NeighborCoordinates () {
List<Vector2Int> neighborCoordinates = new List<Vector2Int> ();
neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x, this.roomCoordinate.y - 1));
neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x + 1, this.roomCoordinate.y));
neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x, this.roomCoordinate.y + 1));
neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x - 1, this.roomCoordinate.y));
return neighborCoordinates;
}
public void Connect (Room neighbor) {
string direction = "";
if (neighbor.roomCoordinate.y < this.roomCoordinate.y) {
direction = "N";
}
if (neighbor.roomCoordinate.x > this.roomCoordinate.x) {
direction = "E";
}
if (neighbor.roomCoordinate.y > this.roomCoordinate.y) {
direction = "S";
}
if (neighbor.roomCoordinate.x < this.roomCoordinate.x) {
direction = "W";
}
this.neighbors.Add (direction, neighbor);
}
public string PrefabName () {
string name = "Room_";
foreach (KeyValuePair<string, Room> neighborPair in neighbors) {
name += neighborPair.Key;
}
return name;
}
public Room Neighbor (string direction) {
return this.neighbors [direction];
}
public void PopulateObstacles (int numberOfObstacles, Vector2Int[] possibleSizes) {
for (int obstacleIndex = 0; obstacleIndex < numberOfObstacles; obstacleIndex += 1) {
int sizeIndex = Random.Range (0, possibleSizes.Length);
Vector2Int regionSize = possibleSizes [sizeIndex];
List<Vector2Int> region = FindFreeRegion (regionSize);
foreach (Vector2Int coordinate in region) {
this.population [coordinate.x, coordinate.y] = "Obstacle";
}
}
}
public void PopulatePrefabs (int numberOfPrefabs, GameObject[] possiblePrefabs) {
for (int prefabIndex = 0; prefabIndex < numberOfPrefabs; prefabIndex += 1) {
int choiceIndex = Random.Range (0, possiblePrefabs.Length);
GameObject prefab = possiblePrefabs [choiceIndex];
List<Vector2Int> region = FindFreeRegion (new Vector2Int(1, 1));
this.population [region[0].x, region[0].y] = prefab.name;
this.name2Prefab [prefab.name] = prefab;
}
}
private List<Vector2Int> FindFreeRegion (Vector2Int sizeInTiles) {
List<Vector2Int> region = new List<Vector2Int>();
do {
region.Clear();
Vector2Int centerTile = new Vector2Int(UnityEngine.Random.Range(2, 18 - 3), UnityEngine.Random.Range(2, 10 - 3));
region.Add(centerTile);
int initialXCoordinate = (centerTile.x - (int)Mathf.Floor(sizeInTiles.x / 2));
int initialYCoordinate = (centerTile.y - (int)Mathf.Floor(sizeInTiles.y / 2));
for (int xCoordinate = initialXCoordinate; xCoordinate < initialXCoordinate + sizeInTiles.x; xCoordinate += 1) {
for (int yCoordinate = initialYCoordinate; yCoordinate < initialYCoordinate + sizeInTiles.y; yCoordinate += 1) {
region.Add(new Vector2Int(xCoordinate, yCoordinate));
}
}
} while(!IsFree (region));
return region;
}
private bool IsFree (List<Vector2Int> region) {
foreach (Vector2Int tile in region) {
if (this.population [tile.x, tile.y] != "") {
return false;
}
}
return true;
}
public void AddPopulationToTilemap (Tilemap tilemap, TileBase obstacleTile) {
for (int xIndex = 0; xIndex < 18; xIndex += 1) {
for (int yIndex = 0; yIndex < 10; yIndex += 1) {
if (this.population [xIndex, yIndex] == "Obstacle") {
tilemap.SetTile (new Vector3Int (xIndex - 9, yIndex - 5, 0), obstacleTile);
} else if (this.population [xIndex, yIndex] != "" && this.population [xIndex, yIndex] != "Player") {
GameObject prefab = GameObject.Instantiate (this.name2Prefab[this.population [xIndex, yIndex]]);
prefab.transform.position = new Vector2 (xIndex - 9 + 0.5f, yIndex - 5 + 0.5f);
}
}
}
}
}
any help would be awesome even if you can point me in the direction to a how to.
Nice procedural dungeon generator! Just as a suggestion, could you cache the first room at the beginning when you are generating the dungeon? Then you can grab the initialRoomForPlayerSpawn coordinates/ position as a reference point for the character placement.
Room initialRoomForPlayerSpawn = null;
while (roomsToCreate.Count > 0 && createdRooms.Count < numberOfRooms) {
Room currentRoom = roomsToCreate.Dequeue ();
this.rooms [currentRoom.roomCoordinate.x, currentRoom.roomCoordinate.y] = currentRoom;
createdRooms.Add (currentRoom);
AddNeighbors (currentRoom, roomsToCreate);
/* Cache First Room */
if(createdRooms != null && createdRooms.Count <= 1) {
initialRoomForPlayerSpawn = currentRoom;
}
}

Why My player character can't change after go to main menu

I have game the name is quiz game RPG, and I have 1 problem with it, the problem is why after pressing to the town(which is the main menu) and change the character, play it again the character is not the current character but previous character, which is the index back to 0.
I have tried to add playerprefs on the start and change index but nothing changed. still back to 0 after that.
Character select script:
private void Start()
{
characterSelect = FindObjectOfType<_CharacterSelect>();
audioManager = FindObjectOfType<AudioManager>();
selectedCharIndex = PlayerPrefs.GetInt("Player",0);
UpdateCharacterUI();
character = charactersList[selectedCharIndex].Character;
isSold = PlayerPrefs.GetInt(selectedCharIndex + "IsSold", 0);
if (selectedCharIndex == 0)
{
if (isSold == 0)
{
PlayerPrefs.SetInt(selectedCharIndex + "IsSold", 1);
}
}
CheckStatus();
CallPlayer();
}
public void CallPlayer()
{
currentCharacter = Instantiate(character, new Vector3(-2.403f, -0.6f, 0f), Quaternion.identity);
}
private void Update()
{
StartCoroutine(SaveCharacter());
}
void CheckStatus()
{
moneyAmount = (int)PlayerPrefs.GetFloat("MoneyAmount");
isSold = PlayerPrefs.GetInt(selectedCharIndex + "IsSold", 0);
if (moneyAmount >= 0)
{
buyButton.interactable = true;
}
else
{
buyButton.interactable = false;
}
if (isSold == 1)
{
buyButton.gameObject.SetActive(false);
}
else
{
buyButton.gameObject.SetActive(true);
}
Debug.Log(moneyAmount);
Debug.Log(isSold);
}
public void LeftArrow()
{
moneyAmountText.text = moneyAmount.ToString() + "$";
audioManager.play("SFX");
selectedCharIndex--;
if (selectedCharIndex < 0)
{
selectedCharIndex = charactersList.Count - 1;
}
CheckStatus();
UpdateCharacterUI();
}
public void RightArrow()
{
moneyAmountText.text = moneyAmount.ToString() + "$";
audioManager.play("SFX");
selectedCharIndex++;
if (selectedCharIndex == charactersList.Count)
{
selectedCharIndex = 0;
}
CheckStatus();
UpdateCharacterUI();
}
public void Buy()
{
audioManager.play("Unlocked");
moneyAmount -= 0;
PlayerPrefs.SetInt(selectedCharIndex + "IsSold", 1);
buyButton.gameObject.SetActive(false);
PlayerPrefs.SetFloat("MoneyAmount", moneyAmount);
moneyAmountText.text = moneyAmount.ToString() + "$";
}
IEnumerator transition()
{
yield return new WaitForSeconds(2f);
Price.text = "Sold!";
}
public void Confirm()
{
audioManager.play("Confirm");
PlayerPrefs.SetInt("Player", selectedCharIndex);
Debug.Log(string.Format("Character{0}:{1} has been choosen", selectedCharIndex, charactersList[selectedCharIndex].CharName));
character = charactersList[selectedCharIndex].Character;
ChangeCharacter();
}
void ChangeCharacter()
{
Vector3 currentPosition = currentCharacter.transform.position;
Destroy(currentCharacter);
currentCharacter = Instantiate(character, currentPosition, Quaternion.identity);
cameraFollow = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CameraFollow>();
cameraFollow.GetPlayer(currentCharacter);
}
IEnumerator SaveCharacter()
{
if (saveChar)
{
saveChar = false;
yield return new WaitForSeconds(0.05f);
currentCharacter = Instantiate(character, new Vector3(-2.47699f, 0.169f, 0), Quaternion.identity);
cameraFollow = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<CameraFollow>();
cameraFollow.GetPlayer(currentCharacter);
}
}
}
For the levelManager:
prvoid Start()
{
_CharacterSelect = FindObjectOfType<_CharacterSelect>();
audioManager = FindObjectOfType<AudioManager>();
selectLevel = FindObjectOfType<SelecLevel>();
gameManager = FindObjectOfType<GameManager>();
FillList();
}
void FillList()
{
Index = 0;
for (int i = 0; i < selectLevel.Levels; i++)
{
LevelButton levelButton = Instantiate(TheButton, Spacer).GetComponent<LevelButton>();
levelButton.LevelIndex = Index;
levelButton.button.onClick.AddListener(() => SelectLevel(levelButton.LevelIndex));
Index++;
}
}
void DeleteAll()
{
PlayerPrefs.DeleteAll();
Application.LoadLevel(0);
}
void SelectLevel(int index)
{
_CharacterSelect.saveChar = true;
selectLevel.levelIndex = index;
Application.LoadLevel("Level " + (index + 1));
switch (selectLevel.levelIndex)
{
case 1:
audioManager.StopPlay("BGM");
audioManager.play("BGM1");
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
}
public void ReseData()
{
DeleteAll();
}
}
the last GameManager :
private void Start()
{
audioManager = FindObjectOfType<AudioManager>();
//questionManager = FindObjectOfType<_questionManager>();
LevelSelect = FindObjectOfType<SelecLevel>();
Select = FindObjectOfType<_CharacterSelect>();
sliderChanges = FindObjectOfType<SliderChanges>();
onlepel = LevelSelect.levelIndex + 1;
IndexLevel = LevelSelect.levelIndex;
getPlayerData();
Timecount = GameObject.FindGameObjectWithTag("TimeCount");
category = FindObjectOfType<_questionManager>().category;
moneyAmount = PlayerPrefs.GetFloat("MoneyAmount");
if (unansweredQuestion == null || unansweredQuestion.Count == 0)
{
thisQuestions = category[IndexLevel].questions;
unansweredQuestion = new List<Question>(thisQuestions);
//TrueAnswerText.text = "CORRECT";
//FalseAnswerText.text = "WRONG!";
//unansweredQuestion = new List<Question>(questions);
}
TrueCount = 0;
if (FactText != null)
setCurrentQuestion();
}
private void Update()
{
moneyText.text = moneyAmount.ToString() + "$";
}
#region MainQuestion
public void getPlayerData()
{
levelindexPlayerPrefs = PlayerPrefs.GetInt("LevelIndex", 0);
}
public void updateLevel(int Index)
{
if (levelindexPlayerPrefs < Index)
{
PlayerPrefs.SetInt("LevelIndex", Index);
levelindexPlayerPrefs = PlayerPrefs.GetInt("LevelIndex");
}
}
public void setCurrentQuestion()
{
Scoretext.text = TrueCount.ToString() + " / " + thisQuestions.Length.ToString();
RandomQuestionIndex = Random.Range(0, unansweredQuestion.Count);
currentQuestion = unansweredQuestion[RandomQuestionIndex];
FactText.text = currentQuestion.fact;
//IsQuestionAvailable = true;
sliderChanges.TimeRemaining = sliderChanges.TimeMax;
}
public IEnumerator TransitionToNextQuestion()
{
unansweredQuestion.Remove(currentQuestion);
answerQuestion = false;
if (unansweredQuestion.Count == 0 || unansweredQuestion == null)
{
count = thisQuestions.Length;
changeLevel = false;
thisQuestions = category[IndexLevel].questions;
unansweredQuestion = new List<Question>(thisQuestions);
//unansweredQuestion = new List<Question>(questions);
count++;
if (count == thisQuestions.Length || CurrentTrueCount == thisQuestions.Length) ;
{
Scoretext.text = TrueCount.ToString() + " / " + thisQuestions.Length.ToString();
changeLevel = true;
//Objective.SetActive(true);
StartCoroutine(EndGame());
Timecount.SetActive(false);
StartCoroutine(EveryChapter());
}
}
yield return new WaitForSeconds(.5f);
setCurrentQuestion();
}
public IEnumerator EndGame()
{
int Currentstar = PlayerPrefs.GetInt("Level" + (IndexLevel + 1));
PlayerPrefs.SetFloat("MoneyAmount", moneyAmount);
if (TrueCount < thisQuestions.Length || TrueCount == thisQuestions.Length - 5)
{
if (Currentstar < 1)
PlayerPrefs.SetInt("Level" + (IndexLevel + 1), 1);
changeLevel = true;
yield return new WaitForSeconds(1f);
Objective.SetActive(true);
yield return new WaitForSeconds(.3f);
audioManager.play("Stars");
Star1.SetActive(true);
}
if (TrueCount > thisQuestions.Length - 4 || CurrentTrueCount <= thisQuestions.Length - 3)
{
if (Currentstar < 2)
PlayerPrefs.SetInt("Level" + (IndexLevel + 1), 2);
changeLevel = true;
yield return new WaitForSeconds(1f);
Objective.SetActive(true);
yield return new WaitForSeconds(.3f);
audioManager.play("Stars");
Star2.SetActive(true);
}
if (TrueCount > thisQuestions.Length - 2 || TrueCount == thisQuestions.Length)
{
if (Currentstar < 3)
PlayerPrefs.SetInt("Level" + (IndexLevel + 1), 3);
changeLevel = true;
yield return new WaitForSeconds(1f);
Objective.SetActive(true);
yield return new WaitForSeconds(.3f);
audioManager.play("Stars");
Star1.SetActive(true);
audioManager.play("Stars");
Star3.SetActive(true);
}
updateLevel(IndexLevel + 1);
getPlayerData();
Debug.Log(levelindexPlayerPrefs);
}
IEnumerator EveryChapter()
{
Scoretext.text = TrueCount.ToString() + " / " + thisQuestions.Length.ToString();
yield return new WaitForSeconds(7f);
}
public void HandleAnswerButton(bool answer)
{
//IsQuestionAvailable = false;
enemyGenerator.SpawnEnemy();
sliderChanges.TimeRemaining = 0;
FactText.text = string.Empty;
if (answer)
{
animator[0].SetTrigger("click");
if (currentQuestion.isTrue)
{
TrueAnswerText.text = "CORRECT";
moneyAmount += .5f;
answerQuestion = true;
TrueCount++;
Isbattle = true;
//Scoretext.text = TrueCount.ToString() + " / " + thisQuestions.Length.ToString();
}
else
{
TrueAnswerText.text = "WRONG!";
Debug.Log("Wrong!");
}
}
if (!answer)
{
animator[1].SetTrigger("Clack");
if (!currentQuestion.isTrue)
{
FalseAnswerText.text = "CORRECT";
moneyAmount += .5f;
Isbattle = false;
answerQuestion = true;
TrueCount++;
Debug.Log("Correct");
Debug.Log(TrueCount);
//Scoretext.text = TrueCount.ToString() + " / " + thisQuestions.Length.ToString();
}
else
{
FalseAnswerText.text = "WRONG!";
Debug.Log("Wrong!");
}
}
Scoretext.text = TrueCount.ToString() + " / " + thisQuestions.Length.ToString();
//StartCoroutine(TransitionToNextQuestion());
}
#endregion
#region Panels
public void Paused()
{
StartCoroutine(Pause());
PausePanel.SetActive(true);
}
IEnumerator Pause()
{
audioManager.play("Confirm");
yield return new WaitForSeconds(.3f);
Time.timeScale = 0f;
}
public void Resume()
{
audioManager.play("Close");
Time.timeScale = 1f;
PausePanel.SetActive(false);
}
public void Back()
{
audioManager.play("Close");
}
public void Confirm()
{
audioManager.play("Confirm");
}
public void Dead()
{
sliderChanges.gameObject.SetActive(false);
DeadPanel.SetActive(true);
HealthBar.SetActive(false);
PauseButton.SetActive(false);
Scoretext.gameObject.SetActive(false);
GoldField.SetActive(false);
Select.saveChar = true;
}
public void TheOptionPanel()
{
audioManager.play("Confirm");
OptionPanel.SetActive(true);
}
public void PG_MainMenu()
{
audioManager.play("Confirm");
PlayGame.SetActive(true);
}
public void ExitGame()
{
audioManager.play("Confirm");
Application.Quit();
}
#endregion
#region TransitionToNextScene
public void ToTheTown()
{
audioManager.StopPlay("BGM1");
audioManager.play("BGM");
audioManager.play("Confirm");
SceneManager.LoadScene(0);
Time.timeScale = 1f;
}
public void NExtLevel()
{
LevelSelect.levelIndex++;
Select.saveChar = true;
audioManager.play("Confirm");
onlepel += 1;
SceneManager.LoadScene("Level " + onlepel);
switch (LevelSelect.levelIndex)
{
case 1:
audioManager.StopPlay("BGM");
audioManager.play("BGM1");
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
}
public void restart()
{
audioManager.play("Confirm");
Select.saveChar = true;
Time.timeScale = 1f;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
#endregion
solved,
it's confusing me all night though
:'D
but it's because I'm just not setting the playerprefs at Savecharacter line at Character select script
selectedCharIndex = PlayerPrefs.GetInt("Player");
character = charactersList[selectedCharIndex].Character;

Unity2D: How do I regenerate player's health after timer countdown is at 0

I have a script that regenerates player's health after 5 seconds:
float counter;
void Update (){
counter += Time.deltaTime;
if(counter > 30minutes){
curHealth++;
counter = 0.0f; }
if(curHealth > 5)
curHealth = 5;
}
Which is attach to my player's health script. I want to start regenerating my player health back when timer is at 0. But I don't know how.
This is my player health script:
//Stats
public int curHealth;
public int maxHealth = 3;
public Collider2D col;
public PlayerHealth playerhealthRef;
public TimeManager countDownTimer;
float counter;
public Animator anima; // drag the panel in here again
private UI_ManagerScripts UIM;
DateTime currentDate;
DateTime oldDate;
private GenerateEnemy generateEnemy = null;
void Start ()
{
curHealth = maxHealth;
currentDate = System.DateTime.Now;
if (countDownTimer != null)
{
// countDownTimer.gameObject.SetActive(false);
countDownTimer.Enable(false);
}
if (GameObject.Find("Spawner"))
{
generateEnemy = GameObject.Find("Spawner").GetComponent<GenerateEnemy>();
}
}
void Update ()
{
counter += Time.deltaTime;
if (curHealth > maxHealth) {
curHealth = maxHealth;
}
if ((curHealth <= 0) && (!countDownTimer.gameObject.activeSelf)) {
Die ();
}
if(counter > 5)
{
curHealth++;
counter = 0.0f;
}
if(curHealth > 3)
curHealth = 3;
}
void Awake()
{
UIM = GameObject.Find ("UIManager").GetComponent<UI_ManagerScripts> ();
}
void Die() {
UIM.EnableBoolAnimator(anima);
PlayerPrefs.SetInt("RemainingLives", curHealth);
PlayerPrefs.Save();
if (generateEnemy != null)
{
generateEnemy.DestroyAllBlobs();
}
if (countDownTimer != null)
{
countDownTimer.Enable(true);
}
}
public void Damage(int dmg)
{
curHealth -= dmg;
}
}
And this is my Timer countdown script:
public Text timer;
int minutes = 1;
int seconds = 0;
float miliseconds = 0;
[Range(1, 59)]
public int defaultStartMinutes = 1;
public bool allowTimerRestart = false;
public bool useElapsedTime = true;
private int savedSeconds = -1;
private bool resetTimer = false;
private DateTime centuryBegin = new DateTime(2001, 1, 1);
private float tickPerSecond = 10000000.0f;
public void Enable (bool enable)
{
gameObject.SetActive(enable);
ResetTime(); // force the timer to restart
}
void Awake ()
{
minutes = defaultStartMinutes;
if (PlayerPrefs.HasKey("TimeOnExit"))
{
miliseconds = PlayerPrefs.GetFloat("TimeOnExit");
savedSeconds = (int)miliseconds;
if (useElapsedTime && PlayerPrefs.HasKey("CurrentTime"))
{
int elapsedTicks = (int)(DateTime.Now.Ticks / tickPerSecond);
int ct = PlayerPrefs.GetInt("CurrentTime", elapsedTicks);
PlayerPrefs.DeleteKey("CurrentTime");
elapsedTicks -= ct;
if (elapsedTicks < miliseconds)
{
miliseconds -= elapsedTicks;
}
else
{
miliseconds = 0;
}
}
minutes = (int)miliseconds / 60;
miliseconds -= (minutes * 60);
seconds = (int)miliseconds;
miliseconds -= seconds;
PlayerPrefs.DeleteKey("TimeOnExit");
}
savedSeconds = 0;
}
public void Update()
{
// count down in seconds
miliseconds += Time.deltaTime;
if (resetTimer)
{
ResetTime();
}
if (miliseconds >= 1.0f)
{
miliseconds -= 1.0f;
if ((seconds > 0) || (minutes > 0))
{
seconds--;
if (seconds < 0)
{
seconds = 59;
minutes--;
}
}
else
{
resetTimer = allowTimerRestart;
}
}
if (seconds != savedSeconds)
{
// Show current time
timer.text = string.Format("{0}:{1:D2}", minutes, seconds);
savedSeconds = seconds;
}
}
void ResetTime()
{
minutes = defaultStartMinutes;
seconds = 0;
savedSeconds = 0;
miliseconds = 1.0f - Time.deltaTime;
resetTimer = false;
}
private void OnApplicationQuit()
{
int numSeconds = ((minutes * 60) + seconds);
if (numSeconds > 0)
{
miliseconds += numSeconds;
PlayerPrefs.SetFloat("TimeOnExit", miliseconds);
if (useElapsedTime)
{
int elapsedTicks = (int)(DateTime.Now.Ticks / tickPerSecond);
PlayerPrefs.SetInt("CurrentTime", elapsedTicks);
}
}
}
}
Thank you :)
Second edit
I tried doing this in my update file:
if (countDownTimer = true)
{
if(counter > 5)
{
curHealth++;
counter = 0.0f;
}
if(curHealth > 3)
curHealth = 3;
}
But I got this error: error CS0029: Cannot implicitly convert type bool' toTimeManager'.
I just wasn't sure of how to go about doing this.?
According to your second edit line 1
if (countDownTimer = true)
should be
if(countDownTimer)
as = operator is only to give a value, and for comparison you use ==, or, if the variable is bool, simply if(var) or if(!var)
Most of your code is useless.
You can use WaitForSeconds(just google it) or you can add LeanTween to your project and use
LeanTweed.DeayedCall(5f, ()=>{ /*code that will be runned after 5 sec will pass*/});
I prefer to use LeanTween.

UI Freeze in SWT

I am new to SWT. I am trying to create a small application. Basically it has two screens. In the first screen I have to take user credentials. It has to be validated. If its successful I have to query a table and build a tree structure. Both validation and building the tree freezes my UI. I searched stackoverflow and google. I got the below options.
Display.getDefault().asyncExec() and starting long running process as separate thread from UI thread.
But still my UI freezes.
When the user clicks on Logon button. I created a thread. As a first step I tried to show a indefinite progress bar using asyncExec. Since I have to access the Uname and Password I have to trigger another asyncexec and perform the login. If its successful populated the tree.
I triggered another asyncExec to close the progress bar.
My UI freezes from Logon click till Tree population completion. Where am I going wrong.
new Thread(new Runnable()
{
private int progress = 0;
private static final int INCREMENT = 10;
#Override
public void run()
{
while (!progressBar.isDisposed())
{
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
if (!progressBar.isDisposed())
progressBar.setVisible(true);
}
});
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
String sAuth = null;
switch(tAuth.getText()){
case "Enterprise": sAuth = "secEnterprise"; break;
case "LDAP": sAuth = "secLDAP"; break;
case "Windows AD": sAuth = "secWinAD"; break;
case "SAP": sAuth = "secSAPR3"; break;
}
try {
log.info("Attempting to create enterprise session");
CoreLogic.logonEnterprise(tUSR.getText().trim(),tPWD.getText().trim(),sAuth,tCMS.getText());
if(CommonVariables.entsession){
log.info("Enterprise session created.");
CoreLogic.getUniverse();
log.info("Populating universe tree");
String[] temp;
for (Entry<Integer, UnvObj> entry : CommonVariables.unvlst.entrySet()) {
UnvObj t = entry.getValue();
temp = t.getPath().split("/");
if (temp[0].equals("Universes")){
int max = temp.length;
int i =0 ;
boolean flag = false;
TreeItem trItem = null;
do{
if(i == 0) {
if(tree.getItemCount() == 0){
flag = false;
}
else
{
for(int k = 0; k < tree.getItemCount(); k++){
if(temp[i].equals(tree.getItem(k).getText())){
i++;
trItem = tree.getItem(k);
flag =true;
break;
}
else
{
flag = false;
}
}
}
}
else{
if(trItem.getItemCount() == 0){
flag = false;
}
else
{
for(int k = 0; k < trItem.getItemCount(); k++){
if(temp[i].equals(trItem.getItem(k).getText())){
i++;
trItem = trItem.getItem(k);
flag =true;
break;
}
else
{
flag = false;
}
}
}
}
}while (flag == true && i < max);
TreeItem Item = null;
if (i == 0){
for (int k = 0; k < max; k++){
if(k == 0) {
Item = new TreeItem(tree,SWT.NONE);
Item.setText(temp[k]);
Item.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
Item.setImage(image);
}else
{
Item = new TreeItem(Item,SWT.NONE);
Item.setText(temp[k]);
Item.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
Item.setImage(image);
}
}
} else if( i < max){
for (int k = i; k < max; k++){
trItem = new TreeItem(trItem,SWT.NONE);
trItem.setText(temp[k]);
trItem.setData("Type","Folder");
Image image = new Image(display,ResourceLoader.load("/images/Fld.png"));
trItem.setImage(image);
}
}
if (i == 0){
Item = new TreeItem(Item,SWT.NONE);
Item.setText(t.getName());
Item.setData("Type",t.getKind());
Item.setData("Mapkey",entry.getKey());
if(t.getKind().equals("Universe")){
Image image = new Image(display,ResourceLoader.load("/images/Unv.ico"));
Item.setImage(image);
}
else{
Image image = new Image(display,ResourceLoader.load("/images/Unx.ico"));
Item.setImage(image);
}
} else
{
trItem = new TreeItem(trItem,SWT.NONE);
trItem.setText(t.getName());
trItem.setData("Type",t.getKind());
trItem.setData("Mapkey",entry.getKey());
if(t.getKind().equals("Universe")){
Image image = new Image(display,ResourceLoader.load("/images/Unv.ico"));
trItem.setImage(image);
}
else{
Image image = new Image(display,ResourceLoader.load("/images/Unx.ico"));
trItem.setImage(image);
}
}
}
}
log.info("Universe Tree Populated.");
sl.topControl =Universe;
Main.layout();
}else
{
log.info("Unable to create enterprise session");
MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
messageBox.setText("Report Extractor");
messageBox.setMessage("Unable to create the enterprise session with the provided credentials. Please verify it.");
messageBox.open();
}
}
catch(Exception exp)
{
log.error("Fail to create enterprise session",exp);
}
}
});
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
if (!progressBar.isDisposed())
progressBar.setVisible(false);
}
});
}
}
}).start();