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

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"

Related

Unity C# script not playing Particle Effect

I created a project using the FPS Microgame in Unity Hub to learn scripting. I'm trying to play a simple particle effect when the player collides with it (in the future I'd love to be able to trigger it from farther away, maybe when crossing into a plane, but I'll learn that later). I created the following script and attached it as a component to the particle effect on the scene:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class portalTrigger : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
ParticleSystem ps = GetComponent<ParticleSystem>();
ps.Play();
}
}
And here's what the particle effect looks like in the Unity Inspector:
The particle effect plays when the game starts if I select Play on Wake so I disabled it because I want it to play when the user collides with it. Any ideas?
Thanks!
First I would add a debug print to verify that a collision is triggered in the onTriggerEnter method.
If that is not the case, I would check that both game objects have a rigid body and a collider. One (and only one) of the two colliders must have the isTrigger flag set.
Here is unity doc link for reference:
https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html
Had you quite made sure that the isTrigger option in object main object has been checked true?
If not then either see the way to check it( What do I mean here is that if you only check isTrigger without making another collision than object won't stop even after the collision. It had been really hectic for me when I started.)
or use the OnCollisionEnter. If none of these happened then try printing to see if they're even colliding or not. C'mon you are trying to become a Unity scripter so best way is to debug anything you doubt about.

AR Foundation - Control Image Tracked Prefab

I am using AR Foundation and I want to control spawned prefab's timeline.
I am trying to create a simple AR app. Imagine I am tracking an image where I am spawning Tracked Image Prefab. Let's say this prefab is a model of a dragon with some fire effect on its timeline. And I want to control the prefabs timeline when it is instantiated by AR Foundation. For example, I want to play fire animation with a button click.
Can I put a listener on the prefab to trigger the timeline in Runtime? How can I do it, please? Is my assumption that I need somehow communicate with the instantiated prefab right?
This is the object and I want to trigger its timeline to play after a button is clicked.
This is the simple code with I wanted to control instantiated prefab's timeline.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
public class TimelineController : MonoBehaviour
{
public PlayableDirector playebleDirector;
public void Play()
{
playebleDirector.Play();
}
}
If I get yoru question correctly, the first you need is something that "prevales" on the scene, if the dragon is created or no, like a Controller.
Your controller can, for example, be the responsible to spawn the dragon. When your dragon is spawned, store that reference (GameObject dragon = Instantiate(dragonPrefab);). It also can have your button reference.
With that you can add your dragons behaviour to the button like:
button.onClick.AddListener(() => { dragon.dragonSpitFire(); }); //with lambda function
button.onClick.AddListener(dragon.dragonSpitFire); //without lambda function
And inside your method "dragonSpitFire" you can put your timeline or animation Start method, like your timeline.Play();
I have solved this problem with Events and Delegates. All initiated objects are subscribed to the event and trigger the function responsible for playing the timeline.

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.

Why when trying to play animation clip nothing happen?

What i want is when running the game that the animation clip will start playing automatically.
I added to the Main Camera a Animation component.
Added in the Inspector to the Animation the clip file name Camera_Sign003 also set the Animations size to 1 and added there the same clip Camera_Sign003.
Also i set to true the Play Automatically.
I also attached a script to the Main Camera:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraPoints : MonoBehaviour
{
public Animation anim;
IEnumerator Start()
{
anim = GetComponent<Animation>();
anim.Play(anim.clip.name);
yield return new WaitForSeconds(anim.clip.length);
}
}
And i checked with a break point it's getting to the line anim.Play....And the length is 10 but nothing happen after 10 seconds.
The animation is a short clip moving the camera from point to point.
The Main Camera is child under ThirdPersonController.
The Animation component is a legacy component and shouldn't be used unless you need to support a legacy tool or project.
What you really need is an Animator component with an Animation Controller for the object. The easiest way to set this up is by selecting the object you want to animate (e.g. Main Camera), opening the 'Animation' window, and clicking the 'Create' button there.
The new animation created will play automatically and loop by default.
More information can be found here: Unity - Manual: Creating a New Animation Clip

Categories

Resources