I am trying to keep going with the roll a ball tutorial and add more levels. I am setting up a scene where you can change the color of the ball. But for some reason, it won’t react unless I hit the button twice, I need to react after once. Here is my script. I am kind of used to the language by now, but we are all human and we can make mistakes.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class ColorBallChange : MonoBehaviour {
public int Colornum;
public Material matofobject;
public Color red;
public Color blue;
public Color green;
public Color pink;
public static ColorBallChange hi;
public void changeColor (int ColorNumP){
if (Colornum == 1) {
matofobject.color = red;
} else if (Colornum == 2) {
matofobject.color = blue;
} else if (Colornum == 3) {
matofobject.color = green;
} else if (Colornum == 4) {
matofobject.color = pink;
}
Colornum = ColorNumP;
}
void Awake(){
if (hi == null) {
DontDestroyOnLoad (gameObject);
hi = this;
} else if (hi != null) {
Destroy (gameObject);
}
if (File.Exists (Application.persistentDataPath + "/ball.cid")) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + "/ball.cid", FileMode.Open);
BallColor col = (BallColor)bf.Deserialize (file);
file.Close ();
Colornum= col.Colornum;
Debug.Log ("Loaded");
}
}
void Start(){
if (Colornum == 1) {
matofobject.color = red;
} else if (Colornum == 2) {
matofobject.color = blue;
} else if (Colornum == 3) {
matofobject.color = green;
} else if (Colornum == 4) {
matofobject.color = pink;
}
}
public void Save(){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create (Application.persistentDataPath + "/ball.cid");
BallColor col = new BallColor ();
col.Colornum = Colornum;
bf.Serialize (file, col);
file.Close ();
Debug.Log ("Saved!");
}
public void Load(){
if (File.Exists (Application.persistentDataPath + "/ball.cid")) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open (Application.persistentDataPath + "/ball.cid", FileMode.Open);
BallColor col = (BallColor)bf.Deserialize (file);
file.Close ();
Colornum= col.Colornum;
Debug.Log ("Loaded");
}
}
}
[Serializable]
class BallColor{
public int Colornum;
}