How a Unity gameobject script check the value of toggle? - c#

We are working on our school project and we are all beginners in Unity and C#.
There is a toggle group with three toggles on our UI panel and three cubes are on the screen. We are having trouble with writing scripts for these cubes. What we want is when the corresponding toggle is on, the color of the cube can be changed by clicking.
For example, when toggle 1 is on, we click cube1 and its color change.
For now, we know how to use the toggle to change color by scripts, but we are not sure how to write a cube script by checking whether the toggle is on or not to change the cube color using mouse clicking.

You can check if a toggle is on or off by using .isOn
using UnityEngine;
using UnityEngine.UI;
public class CheckScript : MonoBehaviour
{
public Toggle myToggle;
void Start()
{
if(myToggle.isOn)
{
Debug.Log("Toggle is on");
}
else
{
Debug.Log("Toggle is off");
}
}
}
But I think what you actually need is this answer https://stackoverflow.com/a/57341924/19611934

Related

How to end a game in C# from a Collision

This is the current script that I have. I have a ball that is player, and I want a collision with my game object tagged as "pit" to end the game. When the game ends I want my game over canvas to pop up. The current script detects the hit when the player rolls over the pit, however, currently, nothing else happens. Both my player and pit have rigidbodies and colliders attached to them. I would really appreciate any help with how to get my code to work properly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Trigger : MonoBehaviour
{
public GameObject GameManager;
private void OnTriggerEnter(Collider other)
{
Debug.Log("hit detected")
if(other.gameObject.tag == "pit")
{
GameManager.GetComponent<Game_Manager>().EndGame();
}
}
}
My EndGame code is in my GameManager script. The is the part of that script that deals with ending the game.
public void EndGame ()
{
player.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePosition;
hasGameStarted = true;
inMenuUI.gameObject.SetActive(false);
inGameUI.gameObject.SetActive(false);
gameOverUI.gameObject.SetActive(true);
}
If I'm correct in interpreting your question, your script successfully detects player death already. If you want a game over screen you have a couple of options:
You can create a UI canvas with a panel on it that obscures the whole screen and put the words Game Over.
Or, probably the better option is to create an entirely new Unity scene and make the Game Over canvas there. When you want to trigger the game over screen you simply use:
Scene manager.LoadScene("Scene name");
You have to add "using UnityEngine.SceneManagement;" at the top of your script. Also note you have to add your Game Over scene to the list of scenes in you game. I believe this can be done by navigating to File>Build settings>scenes and then pressing add open scenes assuming the game over scene is open.

How can I make another scene after scanning the image target

Good day everyone,
how can I make another scene after scanning the image target? So far I can only do the buttons which are the basics and am currently working with c#, visual studio, unity and vuforia.Iv'e done the main menu screen which has the buttons scan and exit. Whenever you click the scan button it will automatically go to the AR camera and my question is how can I make a AR camera which you can scan an image and go to the another scene. No animation or whatsoever, just scan the image and go to another scene. Does someone has an idea of how to make it happen?
so far this is what iv'e coded:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour {
public void System()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1);
}
public void Back()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex -1);
}
public void Exit()
{
Debug.Log("You have exited the app");
Application.Quit();
}
}
In your case you can just create a gameobject as a child of your image target, attach a script, lets say sceneloader.cs and put in the start() method your load-scene-code....but this are total basics. Did you even read the documentation how image targets work?

How do I get touch working in Unity3D?

I'm making an Android app with Unity3D and it works with click detection already, but not with touch. I need touch though for multitouch detection.
What I want: I have my player and 2 images of arrows. One arrow points right and one left. When I touch the left arrow the player should start moving left, when I touch the right arrow the player should start moving right.
But how do I detect which arrow is touched (and held)? All the code I found on Google is too old and not working anymore.
I'm working with C# scripts and it's a 2D game.
Klausar, what you're looking for is .........
A BUTTON (!!!)
it's that easy!
click "add Canvas". (You very likely want "scale to screen size" - select that option.)
click "add Button".
there is no "three" .. go drinking.
In your code, have a routine like this for the right-side button
public void UserClickedRight()
{
Debug.Log("click right whoo!");
}
and have a similar routine for the left-side button.
1. Go to your Button in the editor.
2. Simply drag the script to it and select UserClickedRight !!
You actually do not have to program buttons from scratch :)
This is a basic mechanism of Unity - drag a game object to a "slot" for it in the Editor.
(The game object you drag, has the script in question on it.)
You DO NOT need to go to the level of touch handling to achieve a button!
Now you ask, what about "when holding down on the button"?
It's very easy, you just need to know a couple of things about the Unity "event" system.
In Button, Unity have done all the work for "OnClick":
Since "click" is common, they put that one right in the Inspector panel for you for convenience.
The good news is that Button has many more events you can use.
http://docs.unity3d.com/ScriptReference/UI.Button.html
My guess is you want to use OnPointerDown and OnPointerUp in your case.
To use the other events (which Unity did not bother putting in the Inspector panel) is very simple, you just
1, make a script that references the events you want,
and,
2, you put that script ON the button in question ...
it's that easy.
Step by step explanation:
You're going to be using Unity's event system, so:
using UnityEngine.EventSystems;
Next. You know that a script normally starts like this...
public class FancyButton:MonoBehaviour
The "MonoBehaviour" part just means that it's a c# script which will be "driving a GameObject".
In this case we have to further alert the engine that you will be using those click events. So you add this.
,IPointerDownHandler,IPointerUpHandler
So far we have this
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
Now the easy part.
You just type the two routines which Unity will run for you, when, those things happen.
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
public void OnPointerDown(PointerEventData data)
{
Debug.Log("holy! someone put the pointer down!")
}
public void OnPointerUp(PointerEventData data)
{
Debug.Log("whoa! someone let go!")
}
}
Now all you have to do is drop that script on the Button. Done!
You can put that script on any button, where, you need that functionality.
Next, click on Obi-wan to see where we're at so far!
Finally, it sounds like you want to do something "when the button is being held down". That's just a general programming issue - you'd have a boolean which you turn on and off as the button goes up and down. Let's do it.
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
[System.NonSerialized] public bool mouseIsDownRightNow;
public void OnPointerDown(PointerEventData data)
{
mouseIsDownRightNow = true;
}
public void OnPointerUp(PointerEventData data)
{
mouseIsDownRightNow = false;
}
}
You could access that variable from another script, or whatever you want.
Add the following if you want to run a routine while the button is down:
void Update()
{
if (buttonIsDownRightNow) WhileButtonIsDown();
}
private void WhileButtonIsDown()
{
Debug.Log("THE BUTTON IS DOWN! WHOA!");
}
Try that and watch the console as you hold the button down and up.
Here's an example of something like continually increasing a value while the button is down:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
[System.NonSerialized] public bool buttonIsDownRightNow;
private int countSomething;
public void OnPointerDown(PointerEventData data)
{
buttonIsDownRightNow = true;
}
public void OnPointerUp(PointerEventData data)
{
buttonIsDownRightNow = false;
}
private void WhileButtonIsDown()
{
++countSomething;
}
void Update()
{
if (buttonIsDownRightNow) WhileButtonIsDown();
Debug.Log("value is now " +countSomething.ToString());
}
}
That's all there is to it. Once you really understand events in Unity, there is not much more to learn about Unity.
The only other important topics are Mecanim, shader writing, touch, coroutines, threading, PhysX, native plugins, sprites, networking, dynamic mesh, navigation, VR, AR, animation, inverse kinematics, particles, terrain, IAP, lighting, baking, shadows, MMP, character controllers, and audio. Enjoy!
You should firsty read this.
What you are trying to do is actually simple:
foreach (Touch touch in Input.touches) {
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
if (guiTexture1.HitTest(touch.position)) {
// Maybe move left
}
if (guiTexture2.HitTest(touch.position)) {
// Maybe move right
}
}
}
Edit 1: this code now checks which image is being pressed
Edit 2: Added multitouch support

Get OnMouseDown to work with a 2D Polygon Collider

I'm having a hell of time getting a 2D polygon collider to register a mouse click. I've attached images and code to show where I'm at. I cannot get the click to work.
Ultimately, the thing I'm trying to achieve is to just set the area defined by the collider to be clickable rather than the entire image sprite.
What am I doing wrong here? Need help!
using UnityEngine;
using System.Collections;
public class MouseClick : MonoBehaviour
{
void OnMouseDown()
{
Debug.Log ("Clicked the Collider!");
}
}
I've defined the collider:
I've setup the components for my image:
Set your Canvas "Render mode" to "Screen Space Camera" and attach your camera,
Your using the new uGUI system, you dont even need colliders!
Make your script look like this and you should be able to do it with any object that has Image component. so you can get rid of the collider!
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class MouseClick : MonoBehaviour, IPointerClickHandler
{
void OnPointerClick(PointerEventData data)
{
Debug.Log ("Clicked the Collider!");
}
}
I want to suggest to you a different approach seeing as this uses UGUI.
Attach an EventTrigger script. Then add a new trigger of type PointerClick. Now you can drag an object into that and call any function on that object. This is a very easy and reusable way.
With this in place you can safely remove you rigidbody and collider unless those are needed for something other than mouse interaction.

GameObject to appear when clicking a button in unity3d?

I needed to create UIButton attached to a gameobject.
I'm using a board based game i.e., when ever clicking a button at that time place one object to that particular button.
I am using c# script in unity3d .
void UIBtn(GameObject BName)
{
//here to write Button click event.
}
I'm assuming you mean GUI.Button .
Reading your first sentence I understood that you wanted to create a button where a GameObject is, but reading your second sentence it seems that you want a GameObject to appear when clicking a button. Since I'm not sure, I'll answer both.
To make a GUI button appear at the place the mouse is use something like:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
void OnGUI() {
Vector2 screenPos = Event.current.mousePosition;
GUI.Button ( new Rect(screenPos.x,screenPos.y,100,100),"Hello");
}
}
Attaching a button to a GameObject requires first identifying the GameObject via Physics.Raycast and then getting the GameObject from the HitCollider and then, on the game object's OnGUI loop. constantly translate its world coordinates to screen coordinates to be able to show a button, via GUI.Button.

Categories

Resources