How do I make audio play with GetComponent? (Unity, C#) - c#

I'm making a version of minesweeper in Unity with C# for a project where different audio plays one shot depending on which number is inside the box you click (adjacent to each bomb, e.g. '1' would play a major chord, '2' a minor chord, etc.)
Part of my code that relates to this:
// Different Textures
public Sprite[] emptyTextures;
public Sprite mineTexture;
public AudioSource myFx;
public AudioClip[] audioFiles;
// Load another texture
public void loadTexture(int adjacentCount)
{
if (mine)
GetComponent<SpriteRenderer>().sprite = mineTexture;
else
GetComponent<SpriteRenderer>().sprite = emptyTextures[adjacentCount];
}
I can't seem to get the audio to work. I assume it would be something like this?
GetComponent<SpriteRenderer>().sprite = emptyTextures[adjacentCount];
GetComponent<AudioSource>().clip = audioFiles[adjacentCount];
But I just keep getting errors. I'm very new to C# so any help would be appreciated. Thanks! :)
p.s. I've been using this tutorial to create it: https://noobtuts.com/unity/2d-minesweeper-game
Edit:
Errors:
MissingComponentException: There is no 'AudioSource' attached to the "default" game object, but a script is trying to access it.
There is an audio source (myFx), but when I then remove that and add an audio source directly to the gameobject, I get no errors but no audio plays.

You are on the right track - you specify the clip you want to play with
GetComponent<AudioSource>().clip = audioFiles[adjacentCount];
The only thing left to do is actually play the clip by calling
GetComponent<AudioSource>().Play();

Related

How do I set the target sorting layer in Unity Light2D using Universal Render Pipeline (URP)

I'm making a top-down shooter game and I'm trying to add a muzzle flash by using URP light 2D.
I'm trying to set the target sorting layers for the URP Light2D. I've looked in the documentation and everywhere, but I can't seem to find the code for the target sorting layer. It seems that the target sorting layer can't be changed programmatically. This is a big problem especially when you created the Light2D component in code.
Here is my code:
GameObject MuzzleFlash = new GameObject("MuzzleFlash");
Light2D lightComp = MuzzleFlash.AddComponent<Light2D>();
lightComp.lightType = Light2D.LightType.Point;
// Add the target sorting layers here
MuzzleFlash.transform.position = fromPosition; // From position is a Vector3
I have looked through the Unity forums and found this:
[SerializeField] public int[] m_ApplyToSortingLayers = new int[1];
lightComp.m_ApplyToSortingLayers = new int[] {
SortingLayer.NameToID("someLayer1"),
SortingLayer.NameToID("someLayer2"),
SortingLayer.NameToID("Default"),
};
Source: Can Target Sorting Layer be set in code for Light2D?
But when I plugged that into my code, the console said that
"'Light2D' does not contain a definition for 'm_ApplyToSortingLayers' and no accessible extension method 'm_ApplyToSortingLayers' accepting a first argument of type 'Light2D' could be found".
I also got this message from the console:
"Some scripts have compilation errors which may prevent obsolete API usages to get updated. Obsolete API updating will continue automatically after these errors get fixed."
When will there be a proper API for setting target layers for Light2D? I am new to Unity, so if anyone could help me that would be great.

Unity ProBuilder API changes to mesh won't render even though they are beeing applied

Hi I was trying to setup a system to procedurally generate 3d rooms on Unity.
I used the ProBuilder API to generate a normal cube and that worked fine. But as soon as I want to do any more than that through the API it doesn't work.
For example if I want to flip the normals of the whole mesh I use this code:
for (int i = 0; i < cube.faces.Count; i++)
{
Debug.Log("Face: " + cube.faces[i]);
cube.faces[i].Reverse();
}
If I run the game now the cube still looks as before, but if I try to select single faces it behaves like the code worked. Also if I try to do it manually through the manual ProBuilder tool I have to use the function 2 times to make it work.
To me it seems like the code works but somehow it doesn't get rendered in game afterwards.
Has anybody had the same problem and might be able to help me out?
Cube Generation Function:
void generateBlock(Vector3 size, Vector3 position)
{
cube = ShapeGenerator.GenerateCube(PivotLocation.Center, size);
cube.GetComponent<MeshRenderer>().material = material;
cube.transform.position = position;
}

ARCore Unity adding a new gameobject to an imported prefabs

I've built an AR Portal using this tutorial at https://www.youtube.com/watch?v=1cwm6sCcV_o&list=PLKIKuXdn4ZMhwJmPnYI0e7Ixv94ZFPvEP
The AR Portal is working fine.
But now, I want to add a new gameObject (say a Quad) which will act as a banner screen. I want this banner to be inside the portal.
I want to add WWW.LoadImagesintoTexture script (https://docs.unity3d.com/ScriptReference/WWW.LoadImageIntoTexture.html) to this banner and render online images onto it.
Right now, I am able to get online image onto the banner but, as soon as I enter the portal, the banner disappears. What would be the reason? And how should I find a solution to it?
Please note: We have used Park Assets from the Asset store on Unity.
Check the OnlineIMage Script that I'm using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class onlineimage : MonoBehaviour
{
public Material[] materials;
public string url = “https://docs.unity3d.com/uploads/Main/ShadowIntro.png“;
IEnumerator Start()
{
foreach (var mat in materials)
{
mat.SetInt (“_StencilTest”, (int)CompareFunction.NotEqual);
}
Texture2D tex;
tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
using (WWW www = new WWW(url))
{
yield return www;
www.LoadImageIntoTexture(tex);
GetComponent<Renderer>().material.mainTexture = tex;
}
}
}
First guess would be the material/shader being used.
This tutorial requires each material to have a special shader with a '_StencilTest' property that will toggle based on whether the device is inside the 'other world'.
This will only allow the pixels of the objects to be drawn if they pass the test.
also make sure the portal script knows about the material that should be changed on transition.

GameObject.Find() works in editor, but returns null in build

I'm currently using GameObject.Find() to retrieve an object generated by the Mapbox Unity SDK. The code works fine in the editor, but when I build the project it returns null. The offending code is the following:
GameObject go = GameObject.Find ("16/32699/21126");
if(go != null) {
//do the thing
} else {
Debug.Log("the tile doesn't exist");
}
I've tried building in both WebGL and Native OSX, both with the same result.
in the editor, the exact name of the object I'm looking for in the scene hierarchy is 16/32699/21126. I appreciate that using the forward slash is how you search for sub-children in unity, but it seemed to work fine in the editor.
below is a screenshot of the scene hierarchy.
The behaviour script is attached to the Map object.
Do you know what could be causing this, or if there is another way of searching for the object I'm after?
You can directly access the tile through the map visualises..
example code.
UnwrappedTileId unwrappedTileId = Conversions.LatitudeLongitudeToTileId(latLon.x, latLon.y, (int)_mapManager.Zoom); //either use lat,lon or other way to get unwraptileid
var tile = _mapManager.MapVisualizer.ActiveTiles[unwrappedTileId];//_mapManager is your abstract map
//active tiles is the dictionary created by mapbox sdk to track which tiles are active
if(null!= tile)
{
myModel.transform.SetParent(tile.transform, true);
}
else
{
Debug.Log("Map tile is null");
}

How to change audio output device using VLC.Net

I am able to create media player like app using VLC.Net library. I am now trying to add a feature to be able to select the output device to play the media through. So far no luck.
Has anyone ever done it?
From reading the source code I would try the following. I assume you have a VlcMediaPlayer at hand and created somewhere:
void DoAudio(VlcMediaPlayer player)
{
IAudioManagement audioMgt = player.Audio;
foreach(AudioOutputDescriptions descriptions in audioMgt.Outputs.All){
foreach(AudioOutputDevice device in description.Devices){
//enumerate them for display
string audioName = device.LongName;
// Or set it as output
device.SetAsCurrent();
}
}

Categories

Resources