Several Issues with IPointerClickHandler Unity [duplicate] - c#

This question already has answers here:
How to detect click/touch events on UI and GameObjects
(4 answers)
Closed 4 years ago.
I am trying to create a very simple button in Unity, using the information provided in this question but after a multitude of attempts it won't seem to work.
I have a "button" object, with a SpriteRenderer and BoxCollider2D component, a Physics2DRaycaster attached to my main camera, and the following code attached to the object:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class ButtonController : MonoBehaviour, IPointerClickHandler
{
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("Clicked" + eventData.pointerCurrentRaycast.gameObject.name);
}
}
This is the scene, there is clearly nothing obstructing the button:
There is only the button and the camera in the scene:
And these are the components attached to both the camera and the button:
I'm aware this isn't strictly the kind of question to ask on here but it's been several days now and this should have been something very simple but can not for the life of me see what's gone wrong.

Do you have an Image component added to your object? For the event to trigger you need to have a component that can be a RaycastTarget, ie, it won't trigger from an empty gameObject, it also needs to be child of Canvas.
If you start from fresh scene and create any UI element from the GameObject menu, Unity will create an Event System, Canvas and InputModule components, which is a great start - if you can click the button, you should get your debug if you click on an image with your script - your code is correct.
For a sprite working with the event system, you'll need a physics raycaster and collider. A 3D Box collider works with Physics Raycaster, and 2D Box Collider works with Physics2D Raycaster, but if no collider is present your sprite won't intercept raycasts, they need colliders to work

Related

OnPointerClick function not getting called [duplicate]

This question already has an answer here:
EventSystem OnPointerXXX functions not getting called
(1 answer)
Closed 5 years ago.
I'm working on a mobile game and I need to check if the user touches one of 2 game objects. My script looks like this:
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine;
public class PlayerControl : MonoBehaviour, IPointerClickHandler {
public void OnPointerClick(PointerEventData eventData) {
Debug.Log("Clicked: " + eventData.pointerCurrentRaycast.gameObject.name);
}
}
The code I got from: this stackoverflow post, but it still doesn't work for me.
My 2 game objects have the script, a rigidbody 2d and a box collider 2d..
When I click on the gameobjects, it doesn't log to the console. And the event mask is correct.
Can someone help me?
IPointerClickHandler is part of the EventSystem, so you'll need to have an EventSystem in your scene, as well as a Physics Raycaster attached to your camera to allow the EventsSystem interfaces to work with 3d objects.
Try OnMouseDown() and add this script on the objects you want to click and the objects must have colliders. It should work fine. For more information read the documentation about OnMouseDown() on the link below:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html

Unity 5 UI button function [duplicate]

This question already has answers here:
How to detect click/touch events on UI and GameObjects
(4 answers)
Closed 5 years ago.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public Vector2 jumpForce = new Vector2(0, 300);
public GameObject Egg;
public Transform eggpoint;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp("space") || Input.GetMouseButtonDown(0))
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce(jumpForce);
}
if(Input.GetKeyDown(KeyCode.Return))
{
Instantiate(Egg, eggpoint.position, eggpoint.rotation);
}
So as you guys can see in the separate box how I am instantiating my egg droping code. And I am achieving this by pressing the return or enter button on the keyboard, what I want to ask is how can I use a button to do it rather than the enter. So I have placed a UI button on my game screen but as I am absolute beginner I can't figure out how to connect the button and the function please guide me to the right tutorial.
Jack,
I would highly recommend that you look through the Unity Tutorials as they will guide you through some of the basics of UI development.
See: Unity3D UI Tutorials
In regards to your question:
In Unity, if you click on your button gameobject, in your inspector you should see a button component attached to the gameobject. This button component will have a feature called "On Click" which you can use to trigger an action to occur.
The other way to go about it would be to reference the Button component via code and add an event listener that calls the appropriate function when an event occurs.
I have a short tutorial video that explains components that can be seen here: Video Link
I would this
if (Input.GetKeyDown(KeyCode.Space)) || Input.GetMouseButtonDown(0))
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce(jumpForce);
}

How to play audio in Unity (Click Event Trigger Cardboard SDK)?

I'm using the Cardboard sdk and have configured Gaze Input Module in Event System. Have also added a collider to my object.
I want to look at the object and play audio when I pull the trigger on my Cardboard HMD. However, it's currently not playing.
Can you advise if the problem is with my code:
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class Kim : MonoBehaviour {
public GameObject kkhair;
public AudioSource audio;
void Start() {
audio = GetComponent<AudioSource>();
}
public void speakKim() {
audio.Play();
}
}
This audio does 'play on wake' when that setting is enabled. So I know the file is ok. Just can't make it work for trigger only.
If you have the Cardboard SDK, you should also have the Demo Scene made by Google. There you click a cube that teleports, using the Gaze Input Module. You can use the same mechanism to trigger your audio. The Cube gameObject in that scene has an Event Trigger component that handles the click (and highlighting) for you, and calls a method on another component of the gameObject (in this example the TeleportRandomly() function of the Teleport script attached to the Cube).
In your case, you could change the Pointer Click event handling to speakKim on your script, to make start the audio playing.
You need to attach an "Event Trigger" component to your GameObject.
Select your GameObject in the Hierarchy, click "Add Component", search for "Event Trigger"
Create a new event type of "Pointer Click"
Drag in your Kim script, and choose the method speakKim
Your game object should look something like this:
You must also have an EventSystem in your Hierarchy. If you don't, add one by going to "Create > UI > Event System"

Why is there no camera attached, even if I've attached it?

So, i want to use camera.ViewportToWorldPoint() to show the bottom center bounds of my screen. So, I created a script, add that component to my object that need it.
using UnityEngine;
using System.Collections;
public class PathMovement : MonoBehaviour {
public Camera cam;
private Vector3 bound;
void Awake () {
cam = GetComponent<Camera> ();
}
void Start(){
bound = cam.ViewportToWorldPoint (new Vector3 (0f, 0.5f));
Debug.Log (bound);
}
}
and then, I attach the MainCamera via the GUI
And then, when I run it, there's still an error says :
MissingComponentException: There is no 'Camera' attached to the "RiverPath" game object, but a >script is trying to access it.
You probably need to add a Camera to the game object "RiverPath". Or your script needs to check if >the component is attached before using it.
UnityEngine.Camera.ViewportToWorldPoint (Vector3 position) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineCamera.gen.cs:408)
PathMovement.Start () (at Assets/Scripts/PathMovement.cs:21)
This is quite weird since I've attached the main camera, but somehow unity didn't detect that. I also have tried to put the cam = GetComponent<Camera>(); on Awake() as well as Start(), but none work. :(
Btw, I am making a mobile application on android. And using unity 5.
Is there any way to do it properly??
Thanks.
You're getting the MissingComponentException as there is no Camera attached to that particular GameObject (see the description of the Exception).
What you need to know is that GetComponent only looks for that Component in the current GameObject. Depending on your GameObject hierarchy you may want to use GetComponentInParent or GetComponentInChildren instead.
Or you could also attach the Camera using the Editor (drag and drop). This may not work if you instantiate that Prefab during runtime, but should do just fine when its static in the scene.

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