I am creating a function to change the background image of a toggle button when it is pressed but it is not working out for me.
I currently have this function:
public Image Background1;
public Image Background2;
public Toggle theToggle;
public void ChangeBackground()
{
if (theToggle.isOn) {
theToggle.image () = Background1;
}
else
{
theToggle.image() = Background2;
}
}
My problem is that in the scene view I don't receive the slot option to add an image to Background1 and Background2 like it happens on other scripts. Also the image parameterer is not recognized by the editor despite the fact it is on the scripting reference and that I have added the UI lybrary using:
using UnityEngine.UI;
Also, I tried to put the ChangeBackground() function inside the Update() function like this and I receive a parse error:
public Image Background1;
public Image Background2;
public Toggle theToggle;
void Update ()
{
public void ChangeBackground()
{
if (theToggle.isOn) {
theToggle.image () = Background1;
}
else
{
theToggle.image() = Background2;
}
}
}
This parse error is very strange because this is the way i did in other scripts. Can you help me?
Well for one, you have a compiler error because you're attempting to call the function "image" and assign it a value at the same time. My guess is you wanted to set the image attribute to some Sprite type variable "Background1"
So you'd change that like this:
public void ChangeBackground()
{
if (theToggle.isOn) {
theToggle.image = Background1;
}
else
{
theToggle.image = Background2;
}
}
}
Now, when there is a compiler error, the inspector will not update with new fields from a script. So if you have declared variables somewhere in your script (usually after the class declaration) like so:
public Image background1;
public Image background2;
They will appear in the inspector, waiting to be set, as long as you have no compiler errors and they are public
Also, you can't put a function declaration, nor would you want to, in C# and most programming languages.
You MUST drag the ChangeBackground function ON TO YOUR TOGGLE. Drag it to here...
Note! the following is highly advanced information, not immediately relevant to Grow's question as such.
An easy way to apply the ChangeBackground function whenever the toggle is toggled, you could simply do it in script by including these two functions:
void OnEnable()
{
theToggle.onValueChanged += ChangeBackground
}
void OnDisable()
{
theToggle.onValueChanged -= ChangeBackground
}
Related
I tried to toggle the visibility of the object with the following code.
However, when I right-clicked the first time, the object was hidden, but when I right-clicked the second time, the object was not displayed.
The object should appear on the second right click.
What's wrong with this code?
using UnityEngine;
public class EnvironmentSettings : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Debug.Log(this.gameObject.activeSelf);
if(this.gameObject.activeSelf)
{
this.gameObject.SetActive(false);
}
else
{
this.gameObject.SetActive(true);
}
}
}
}
If you disable the game object that hold the script, it can't work anymore since it's not active!
That's why you can hide the object, but not wake it up.
Use a TargetGameObject field, that you'll enable/disable. Like this :
public class EnvironmentSettings : MonoBehaviour
{
public GameObject TargetGameObject;
private void Update()
{
if (Input.GetMouseButtonDown(1))
TargetGameObject.SetActive(!TargetGameObject.activeSelf);
}
}
Put this script on a GameManger, or at least something that won't be disabled during play time, such as the main camera. Then slide your TargetGameObject to toggle into the field from the scene view.
I'm working on creating a master script in Unity to control the other scripts. I'm stuck at one part which is the master script can call function from the others.
For example below is script B
public class B
{
void Test()
{
Dosomething;
}
}
Script A will be the master one that control script B. Is there any way that you can call Test() in script B like A.Test()?
I tried interface but then I still have to create another Test() function inside script A. This will be troublesome if I include more scripts with more functions.
Any advice would be appreciated.
This is from the Unity tutorials. Should be a good start...
public class UsingOtherComponents : MonoBehaviour
{
public GameObject otherGameObject;
private AnotherScript anotherScript;
private YetAnotherScript yetAnotherScript;
private BoxCollider boxCol;
void Awake ()
{
anotherScript = GetComponent<AnotherScript>();
yetAnotherScript = otherGameObject.GetComponent<YetAnotherScript>();
boxCol = otherGameObject.GetComponent<BoxCollider>();
}
void Start ()
{
boxCol.size = new Vector3(3,3,3);
Debug.Log("The player's score is " + anotherScript.playerScore);
Debug.Log("The player has died " + yetAnotherScript.numberOfPlayerDeaths + " times");
}
Okay, so the first things you should be aware about is that you really cant use static classes and functions in unity. That has something to do with every component on a gameobject essentially being a script the is instanced. So simply typing "using ScriptB" on the top and the calling the function like "ScriptB.Test();" really wont do anything.
What you need to do is to pass in a Script B reference as a variable in to Script A and then assign either drag it in editor or assign it via Script A. But in any case both scripts have to be in the same scene and assign to any game objects that are in that scene (they dont have to be on the same one)
So the final solution would look like this:
public class A
{
public B refToB;
void Start()
{
//we call the function here
refToB.Test();
}
}
public class B
{
public void Test(){
//we can do something here :)
}
}
Only thing for this to work is thet you need to assign the variable refToB through the inspector panel in the editor. A simple drag and drop action.
Hope it helps :)
I need to stop/resume the rotation of a fan when a certain key is pressed, so I wrote this C# code:
public bool rotationFlag = false;
void Update()
{
if(rotationFlag)
{
fan.transform.Rotate(Vector3.up, rotationAngle);
}
}
public void commuteFan()
{
rotationFlag = !rotationFlag;
}
cummuteFan() method is called when I press the button.
the variable starts on false and the fan correctly doesn't ratate, when I hit the button, the method is called, the variable values changes and the starts to rotate, but if I want to stop it, it doesn't work anymore. debug tells me that the value is correctly changed to false in commuteFan() but update() continues to read the old value (true) and the fan doesn't stop.
[SOLVED] I don't know why, but I created a class with only the bool along with getter/setter methods in it and it works know
So you had your variable as public, which means that any other part of the project could easily edit it. In your case you were changing it via the editor.
To avoid this kind of problems in the future try using protection.
public class Test : MonoBehaviour
{
private bool isRotating = false;
public void setIsRotating(bool status)
{
isRotating = status;
}
public bool getIsRotating()
{
return isRotating;
}
}
Coding like this will save you a lot of headaches later on.
I am trying to access a function, with a bool parameter, from one script to another and just can't get it to work. I have been looking around to try to understand what i am doing wrong.
Here is the script i am calling:
public class MainScript : MonoBehaviour {
public void ManageBoxCollider2D (bool shouldColliderBeEnabled) {
print (">>>>>>>>>>>>>>>>ManageBoxCollider2D: " + shouldColliderBeEnabled);
}
}
I am trying to call it from this script:
public class Sidebar1_Script : MainScript {
public MainScript mainScript;
void Start () {
mainScript.ManageBoxCollider2D (true);
}
}
There is a lot of other stuff in the scripts as well but this is what matters for this question
In the "Sidebar1_Script" I am trying to access "ManageBoxCollider2D" in "MainScript" but it does not work.
I do get the following message:
Object reference not set to an instance of an object
...which i do understand but can't figure out what i am doing wrong.
I would appreciate some help how to do this.
Thanks
It's because unity doesn't know what script that is. If you see in the inspector you're gonna find that public variable MainScript is still empty, also you can't assign scripts in the inspector (I don't know why though, when you drag it there it won't fit in).
Instead change your Sidebar1_Script like this:
public GameObject obj;
void Start () {
MainScript main = obj.gameObject.GetComponent<MainScript>();
main.ManageBoxCollider2D(true);
}
And then assign the game object of obj in the inspector (drag the game object to the public variable).
So I have this problem where I have a variable called StarBounds in my main game class file. The file is now called MainGameClass.cs with namespace StarCatcher.
I have made a class to detect if the mouse is hovered over the StarBounds variable and then clicks. On click I would like to edit the StarBounds variable from this other class called GameFunctions.cs.
I am able to do something like...
MainGameClass mgc = new MainGameClass();
The when the hover and click event is triggered I can type in without errors:
mgc.StarBounds = new rectangle(0,0,0,0);
But in the actual game it does not change. And also I sometimes get errors when doing the "mgc.StarBounds = new rectangle(0,0,0,0);" saying it doesn't have an object reference.
I think this is most likely just a scope issue. The exception is caused because mgc is null. Make sure that GameFunctions has not declared a local copy of MainGameClass and is referencing a pre-existing instance. Otherwise, use a static variable for StarBounds as shown in the example. Example,
public class MainGameClass {
public static Rectangle StarBounds;
public void HandleInput () {
// if GameFunctions.ClickedWithinStarBounds(mouse)
// GameFunctions.OnClickStarBounds()
}
}
public class GameFunctions {
public static void ClickedWithinStarBounds(MouseState mouse) {
// create a rectangle around the mouse (ie. cursor) for the detection area
// return left mouse button is down or pressed && IsWithinStarBounds
}
public static bool IsWithingStarBounds(Rectangle area) {
return (MainGameClass.StarBounds.Intersects(area);
}
public static void OnClickStarBounds() {
MainGameClass.StarBounds = Rectangle.Empty;
}
}