OnPointerClick function not getting called [duplicate] - c#

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

Related

OnCollisionEnter2D is not being called

I'm fairly new to Unity and I've decided to work on a simple 2d platformer from youtube tutorials.
Everything works fine until I start using collisions. My problem isn't only that it doesn't work, It's that it doesn't appear at all on auto-complete.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class finishLine : MonoBehaviour
{
void Start()
{
}
void Update()
{
}
private void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.CompareTag("Player")) {
SceneManager.LoadScene("level2");
}
}
}
I've also added rigid bodies and box colliders to both objects (player and finish line).
Anyone know what's wrong?
Make sure that you used BoxCollider2D and not the 3D one.
If the autocomplete doesn't work try restarting VisualStudio or whatever IDE you use. If that doesn't work look in the Unity Settings under External Tools and try regenerating project files. That works for me sometimes.
So a couple things you might want to look into to fix this are:
Check if you have the right colliders on both your gameobjects (in this exmaple box collider 2D I assume)
Check if either of your colliders has the "Is Trigger" box check or not. If yes then uncheck it
Make sure your player gameobject has the "Player" tag and the same as the tag you compare in your script because compare tag is case sentitive
Check if you have your finishLine script on the object you want as the root object meaning it's the parent of all the other one inside it and has no parent (this doesn't need to be the case all the time but in this scenario it might help fix the problem)
Did you check the trigger box in the colliders?
Does any one of those objects have a rigid body?
Did you have other functions that destroyed the character when it reaches the destination that is meant to be the trigger?
You can try to set up a two new cubes for testing purposes to narrow down the problem.

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.

Several Issues with IPointerClickHandler Unity [duplicate]

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

Trying to load a new scene when I enter a cube in Unity

So i have this code to enter a new scene:
using System.Collections;
using UnityEngine;
// add this line to use the SceneManagment library
using UnityEngine.SceneManagement;
public class LoadScenes : MonoBehaviour {
[SerializeField] private string loadLevel;
void onTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
SceneManager.LoadScene (loadLevel);
}
}
}
I then add this script to the cube and select it a trigger. I then type in the scene that I want it to send me too, but when i walk into it nothing happens at all. I have tried different variations but it just doesnt seem to work.
My character that I am using is a unity asset called man in suit but I have selected its tag as "Player". Any suggestions would be great!
The Handler for your trigger won't be invoked
As Sunimal allready noted you need to fix the typo.
void OnTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
SceneManager.LoadScene (loadLevel);
}
}
Ensure your Scene is included and checked in the Build Settings
As you can see in the Screenshot below i have added a SampleScene to my build settings. There are 2 ways of adding scenes into the build
By clicking "Add Open Scenes" you can add the scene which is
currently open to that list.
Drag & Drop the scene from your ProjectView into the List
Ensure your SceneName is set correctly
Your loadLevel field would in my case need to have the value "Scenes/SampleScene".
[SerializeField] private string loadLevel;
The player needs a collider
As you use the OnTriggerEnter method, your Player object needs to have some sort of Collider attached to it. This can be a BoxCollider, SphereCollider or some other Collider. Note that the "Is Trigger" checkbox needs to be checked. Else it won't act as trigger.
Edit: Thanks Eddge for correcting me. See this answer for a deeper explanation about Triggers.
Programatically ensure you have a BoxCollider component beside your LoadScenes component
You can add the RequireComponent Attribute at your class. It basically ensures you have the given type added as a component. This will also automatically add a box collider to an object, when you add this script.
[RequireComponent(typeof(BoxCollider))]
public class LoadScenes : MonoBehaviour {
/// your other code is here
}
Thanks to Sunimal for this hint!
What if that did not solve the problem?
If all this does not help, please provide an screenshot of the inspector of your Playerobject. That way we can see what components are attached to that object and how they are "configured"
SceneManagement
To use the SceneManager to load a scene you must ensure that your scene is in the build settings, per Tobias's answer.
Triggers
In all software development case does matter and it is incredibly important. OnTriggerEnter is not the same as onTriggerEnter, also note OnTriggerEnter(Collider col) is not the same as OnTriggerEnter(Collision col)
In order to use any of the trigger methods there are 3 things that are a must:
Both Objects have to have colliders.
One of the colliders have to be marked as a trigger.
One of the objects have to have a rigidbody.
The trigger event is sent to the object with the rigidbody and whatever object is the trigger, in the circumstance that both objects are triggers both will receive it.

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);
}

Categories

Resources