SWT StyledText - How To Indent/Un-Indent Selected Text With Tab Or Shift+Tab Keys - eclipse

Using the Eclipse SWT StyledText widget, how can you indent/un-indent a selected block of text with the tab or shift+tab keys?

This seems to do the trick...
protected Control createContents(Composite parent){
......
//add the listeners...
text_code_impl.addVerifyKeyListener(new VerifyKeyListener() {
public void verifyKey(VerifyEvent e) {
if (e.keyCode == SWT.TAB) {
if ((e.stateMask & SWT.SHIFT) != 0){
e.doit = text_code_impl_shift_tab_pressed();
} else {
e.doit = text_code_impl_tab_pressed();
}
}
}
});
text_code_impl.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
e.doit = false; //allows verifyKey listener to fire
}
}
});
}
boolean text_code_impl_tab_pressed()
{
if (text_code_impl.getSelectionText().equals("")){
return true;
}
Point range = text_code_impl.getSelectionRange();
int start = range.x;
int length = text_code_impl.getSelectionCount();
String txt = text_code_impl.getText();
while (start > 0 && txt.charAt(start-1) != '\n') {
start--;
length++;
}
int replace_length = length;
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
String sel_text = text_code_impl.getSelectionText();
String[] lines = sel_text.split("\n");
String new_text = "";
for (int x=0; x < lines.length; x++){
if (x > 0){
new_text += '\n';
}
new_text += '\t';
length++;
new_text += lines[x];
}
text_code_impl.replaceTextRange(start, replace_length, new_text);
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
return false;
}
boolean text_code_impl_shift_tab_pressed()
{
if (text_code_impl.getSelectionText().equals("")){
return true;
}
Point range = text_code_impl.getSelectionRange();
int start = range.x;
int length = text_code_impl.getSelectionCount();
String txt = text_code_impl.getText();
while (start > 0 && txt.charAt(start-1) != '\n') {
--start;
++length;
}
int replace_length = length;
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
String sel_text = text_code_impl.getSelectionText();
String[] lines = sel_text.split("\n");
String new_text = "";
for (int x=0; x < lines.length; x++){
if (x > 0){
new_text += '\n';
}
if (lines[x].charAt(0) == '\t'){
new_text += lines[x].substring(1);
length--;
} else if (lines[x].startsWith(" ")){
new_text += lines[x].substring(1);
length--;
} else {
new_text += lines[x];
}
}
text_code_impl.replaceTextRange(start, replace_length, new_text);
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
return false;
}

Related

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

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.

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.

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;

Spawning random platforms in unity

So in my quest to make a game like the very popular zigzag game, I am stuck at randomly generating platforms. The platforms generate randomly in X,-X,Z,-Z directions. I have written my code where it generates the platforms. I might have taken a very long approach (alternative approaches if any)
void Start ()
{
lastPos = platform.transform.position;
size = platform.transform.localScale.x;
InvokeRepeating("SpawnXZ",1f,0.2f);
}
void SpawnX()
{
Vector3 pos = lastPos;
pos.x += size;
lastPos = pos;
Instantiate(platform, pos, Quaternion.identity);
}
void SpawnZ()
{
Vector3 pos = lastPos;
pos.z += size;
lastPos = pos;
Instantiate(platform, pos, Quaternion.identity);
}
void SpawnNegX()
{
Vector3 pos = lastPos;
pos.x -= size;
lastPos = pos;
Instantiate(platform, pos, Quaternion.identity);
}
void SpawnNegZ()
{
Vector3 pos = lastPos;
pos.z -= size;
lastPos = pos;
Instantiate(platform, pos, Quaternion.identity);
}
void SpawnXZ()
{
int rand = Random.Range(0, 6);
if (rand < 3)
{
SpawnX();
}
else if(rand >= 3)
{
SpawnZ();
}
if(--counter == 0) { CancelInvoke("SpawnXZ"); };
if(counter == 0)
{
counter = 25;
int r = Random.Range(0,2);
if(r == 0)
{
InvokeRepeating("SpawnNegXZ",0f,0.2f);
}
else
{
InvokeRepeating("SpawnXNegZ",0f,0.2f);
}
}
}
void SpawnNegXZ()
{
int rand = Random.Range(0, 6);
if (rand < 3)
{
SpawnNegX();
}
else if(rand >= 3)
{
SpawnZ();
}
if(--counter == 0) { CancelInvoke("SpawnNegXZ"); };
if(counter == 0)
{
counter = 25;
int r = Random.Range(0,2);
if(r == 0)
{
InvokeRepeating("SpawnXZ",0f,0.2f);
}
else
{
InvokeRepeating("SpawnNegXNegZ",0f,0.2f);
}
}
}
void SpawnXNegZ()
{
int rand = Random.Range(0, 6);
if (rand < 3)
{
SpawnX();
}
else if(rand >= 3)
{
SpawnNegZ();
}
if(--counter == 0) { CancelInvoke("SpawnXNegZ"); };
if(counter == 0)
{
counter = 25;
int r = Random.Range(0,2);
if(r == 0)
{
InvokeRepeating("SpawnXZ",0f,0.2f);
}
else
{
InvokeRepeating("SpawnNegXNegZ",0f,0.2f);
}
}
}
void SpawnNegXNegZ()
{
int rand = Random.Range(0, 6);
if (rand < 3)
{
SpawnNegX();
}
else if(rand >= 3)
{
SpawnNegZ();
}
if(--counter == 0) { CancelInvoke("SpawnNegXNegZ"); };
if(counter == 0)
{
counter = 25;
int r = Random.Range(0,2);
if(r == 0)
{
InvokeRepeating("SpawnNegXZ",0f,0.2f);
}
else
{
InvokeRepeating("SpawnXNegZ",0f,0.2f);
}
}
}
I have clubbed xz, -xz , x -z and -x -z. I call platform spawning in X and Z direction first, then switching to -XZ or x -Z and so on. But there are 2 main issues.
PS : those small black squares are nothing but diamonds (ignore them).
They either form a 2X2 block or overlap each other.
How do I avoid these? or is there a simpler way of generating platforms that I am missing.
You need an array to indicate which tiles are occupied:
bool[,] tiles = new bool[N,N];
or a dictionary
Dictionary<XZ, bool> tiles = new Dictionary<XZ, bool>();
public struct XZ { public int X; public int Z; }
whenever a tile is spawned check the value to see if it is possible to spawn or not:
void SpawnXZ()
{
int x = (int) (lastpos.x / size);
int z = (int) (lastpos.z / size);
int rand = Random.Range(0, 6);
if (rand < 3 && !tiles[x + 1, z])
{
SpawnX();
tiles[x + 1, z] = true;
}
else if(rand >= 3 && && !tiles[x, z + 1])
{
SpawnZ();
tiles[x, z + 1] = true;
}
else
{
...
}
Note that this code will not work, and it's just a starting point for you to develop it further.

to upload two(photo and signature) image only in database from one page using c#

There is a page where I've to upload and view photo and signature (the snapshot of the page is attached )but whenever i click the view button the path to the image gets clear and the binary format of the image is saved something like 0x(only this much is saved in database nothing else) format in the database .And the 2nd thing is that both photo and signature are to be seen individually without saving in database.please suggest me a solution for this please.
code
protected void pichck()
{
string picextension = System.IO.Path.GetExtension(imgflup.PostedFile.FileName.ToString()).ToLower();
fs = imgflup.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
picbyte = br.ReadBytes((Int32)fs.Length);
byte[] picarray=new byte[]{255,216,255};
//Boolean match = true;
//int i;
//for (i = 0; i <= picarray.Length - 1;i=i+1 )
//{
// if(picarray[i]!=picbyte[i])
// {
// match = false;
// break;
// }
//}
//if (match == true)
//{
if (picextension == ".jpg" || picextension == ".jpeg")
{
if (imgflup.HasFile == true)
{
if (imgflup.PostedFile.ContentLength < 20000 & imgflup.PostedFile.ContentLength > 50000)
{
Response.Write("<script>alert('the file should be of size 20 mb to 50mb ')</script>");
check();
return;
}
else
{
string base64String = Convert.ToBase64String(picbyte, 0, picbyte.Length);
picimg.ImageUrl = "data:image/png;base64," + base64String;
Label1.Visible = true;
Label1.Visible = true;
Label1.Text = imgflup.PostedFile.FileName;
}
}
//}
else
{
Response.Write("<script>alert('the file should be of jpg or jpeg format')</script>");
check();
return;
}
}
else
{
Response.Write("<script>alert('Please Upload a file')</script>");
check();
return;
}
}
protected void signchckt()
{
string signextension = System.IO.Path.GetExtension(signflup.PostedFile.FileName.ToString()).ToLower();
fs1 = signflup.PostedFile.InputStream;
BinaryReader br1 = new BinaryReader(fs1);
signbyte = br1.ReadBytes((Int32)fs1.Length);
//Boolean match = true;
//int i;
//byte[] signarray=new byte[]{255,216,255};
//for (i = 0; i <= signarray.Length - 1;i=i+1 )
//{
// if(signarray[i]!=signbyte[i])
// {
// match = false;
// break;
// }
//}
//if (match == true)
//{
if (signflup.HasFile == true)
{
if (signextension == ".jpg" || signextension == ".jpeg")
{
if (signflup.PostedFile.ContentLength < 20000 & signflup.PostedFile.ContentLength > 50000)
{
Response.Write("<script>alert('the file should be of size 20 mb to 50mb ')</script>");
check1();
return;
}
else
{
string base64String = Convert.ToBase64String(signbyte, 0, signbyte.Length);
signimg.ImageUrl = "data:image/png;base64," + base64String;
Label2.Visible = true;
Label2.Visible = true;
Label2.Text =signflup.PostedFile.FileName;
}
}
else
{
Response.Write("<script>alert('The signature should be of jpg or jpeg type')</script>");
check1();
return;
}
}
//}
else
{
Response.Write("<script>alert('Please Upload a file')</script>");
check1();
return;
}
}
protected void imgviewbtn_Click(object sender, EventArgs e)
{
pichck();
}
protected void signviewbtn_Click(object sender, EventArgs e)
{
signchckt();
}
protected void updtbtn_Click(object sender, EventArgs e)
{
Int64 aplicationid = Convert.ToInt64(Session["ID"].ToString());
if (Session["ID"].ToString()=="")
{
Response.Write("<script>alert('There is no Application Id')</script>");
Response.Redirect("~/home.aspx");
}
else
{
using (obj.con)
{
pichck();
signchckt();
obj.con.Open();
obj.cmd = new SqlCommand("spPhotoandsignature",obj.con);
obj.cmd.CommandType = System.Data.CommandType.StoredProcedure;
obj.cmd.Parameters.AddWithValue("#Application_Id", aplicationid);
obj.cmd.Parameters.AddWithValue("#Pic_Scan",SqlDbType.Binary).Value =picbyte;
obj.cmd.Parameters.AddWithValue("#Pic_Size", fs);
obj.cmd.Parameters.AddWithValue("#Sign_Scan",SqlDbType.Binary).Value =signbyte;
obj.cmd.Parameters.AddWithValue("#Sign_Size", fs1);
obj.cmd.Parameters.AddWithValue("#Type", System.IO.Path.GetExtension(imgflup.PostedFile.FileName.ToString()).ToLower());
int a= obj.cmd.ExecuteNonQuery();
if (a == 1)
{
Response.Write("<script>alert('your data Submitted successfully')</script>");
Response.Redirect("~/Report.aspx");
}
}
}
}
problempage.png