Is there a way in Unity to set a Script as an AudioSource?
I have a Script which produces Sound, i now want to Visualize this, but with GetComponent i only get a null value.
I have tried with GetComponent but for that i need to set the Script as the Source, and it already worked with AudioListeners but i need the AudioSource to also visualize it. I have used several online tutorials, but no one uses a Script as Source.
I can only see one solution left, which i want to avoid ,which would be writing the data from the AudioSource in a file, and generating the Visualization that way.
Edit: I have tried what DareerAhmadMufti suggested:
Sadly it still doesn't work.
public class AudioGaudioGenerator : MonoBehaviour
{
private Graph graph;
public AudioSource _audioSource;
float[] farr = new float[4096];
void Start()
{
graph = this.GetComponentInChildren<Graph>();
_audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
GetSpectrumAudioSource();
if (graph.showWindow0)
{
graph.SetValues(farr);
}
}
void GetSpectrumAudioSource()
{
_audioSource.GetOutputData(farr, 0);
}
This is the Script for the AudioGenerator
You want to use a script for audio visualization, but you only get a null value using the "GetComponent" method. You can create an empty object in the scene with position coordinates (0,0,0) and rename it Audio Visualization, and add LineRenderer and AudioSource components to it.Create a red shader and assign it to LineRenderer.
Create a cube, then create a green shader and assign it to the cube, drag it into a prefab cube.
write scripts:
public class AudioVisualization : MonoBehaviour
{
AudioSource audio;//Sound source
float[] samples = new float[128];//The length of the array to store the spectrum data
LineRenderer linerenderer;//Draw line
public GameObject cube;//cube prefab
Transform[] cubeTransform;//Position of cube prefab
Vector3 cubePos;//The middle position, used to compare the cube position with the spectral data of this frame
// Use this for initialization
void Start()
{
GameObject tempCube;
audio = GetComponent<AudioSource>();//Get the sound source component
linerenderer = GetComponent<LineRenderer>();//Get the line drawing component
linerenderer.positionCount = samples.Length;//Set the number of segments of the line segment
cubeTransform = new Transform[samples.Length];//Set the length of the array
//Move the gameobject mounted by the script to the left, so that the center of the generated object is facing the camera
transform.position = new Vector3(-samples.Length * 0.5f, transform.position.y, transform.position.z);
//Generate the cube, pass its position information into the cubeTransform array, and set it as the child object of the gameobject mounted by the script
for (int i = 0; i < samples.Length; i++)
{
tempCube=Instantiate(cube,new Vector3(transform.position.x+i,transform.position.y,transform.position.z),Quaternion.identity);
cubeTransform[i] = tempCube.transform;
cubeTransform[i].parent = transform;
}
}
// Update is called once per frame
void Update()
{
//get spectrum
audio.GetSpectrumData(samples, 0, FFTWindow.BlackmanHarris);
//cycle
for (int i = 0; i < samples.Length; i++)
{
//Set the y value of the middle position according to the spectrum data, and set the x and z values according to the position of the corresponding cubeTransform
//Use Mathf.Clamp to limit the y of the middle position to a certain range to avoid being too large
//The more backward the spectrum is, the smaller
cubePos.Set(cubeTransform[i].position.x, Mathf.Clamp(samples[i] * ( 50+i * i*0.5f), 0, 100), cubeTransform[i].position.z);
//Draw a line, in order to prevent the line from overlapping with the cube, the height is reduced by one
linerenderer.SetPosition(i, cubePos-Vector3.up);
//When the y value of the cube is less than the y value of the intermediate position cubePos, the position of the cube becomes the position of the cubePos
if (cubeTransform[i].position.y < cubePos.y)
{
cubeTransform[i].position = cubePos;
}
//When the y value of the cube is greater than the y value of the cubePos in the middle position, the position of the cube slowly falls down
else if (cubeTransform[i].position.y > cubePos.y)
{
cubeTransform[i].position -= new Vector3(0, 0.5f, 0);
}
}
}
}
Hook the script on Audio Visualization and assign the prefab cube to the script. Import an audio resource and assign the audio resource to the audiosouce component.
The playback effect is as follows
You cannot use a script as an AudioSource. There is already an AudioSource script. If an object contains the AudioSource script, then you are able to access with GetComponent<AudioSource>(). But it ust already be on the object.
Your question is quite ambiguous. you can't use your custom script as AudioSource, as it is a sealed class.
If you want to get access data of the audioClip or audioSource, add AudioSource component to same object in which your script is attached. like:
make a public AudioSource variable in your script and assign the AudioSource component, as shown above in screenshot.
In this way you will be able to access the data you want in you custom scripts via that variable.
Related
I have a 2D brick breaker style game in Unity where you get to choose the angle of your shot before each turn with the mouse. I'd like to show an accurate trajectory prediction of what a ball will do while the player is aiming, up to maybe 200 frames of ball movement (for now). This involves potentially bouncing off the top, left, and right walls, and any bricks.
I'm using a physics simulation and line renderer to accomplish this but can't get it to work correctly.
It's supposed to copy the gun, walls, and bricks into a virtual Scene, launch a ball in the angle the player is aiming, simulate 200 frames of movement, and plot those in a line renderer.
Here is an abridged version of the game code, reduced to just focus on the aiming and physics simulation for the 1st turn. When I run it, it simply plots the 200 points of the line renderer in the same coordinates as the gun.
What am I doing wrong? Thank you!
using UnityEngine;
using UnityEngine.SceneManagement;
public class Aim3 : MonoBehaviour
{
private Vector3 gunPosScreenV3, aimPointScreenV3,
aimPointWorldV3, aimDirectionV3;
private Vector2 ballDirection, ballVelocity;
[SerializeField] private GameObject gun, walls, bricks;
Camera cam;
LineRenderer lr;
// For Physics Scene
private int maxPhysicsFrameIterations = 200;
private Scene simulationScene;
private PhysicsScene2D physicsScene;
[SerializeField] private GameObject ballPrefab;
private GameObject ghostObj;
void Start()
{
lr = GetComponent<LineRenderer>();
lr.enabled = true;
cam = Camera.main;
CreatePhysicsScene();
}
void Update()
{
DrawTrajectory();
}
// This is run once to create a duplicate of the game board for the physics simulation
private void CreatePhysicsScene()
{
simulationScene = SceneManager.CreateScene("Simulation", new CreateSceneParameters(LocalPhysicsMode.Physics2D));
physicsScene = simulationScene.GetPhysicsScene2D();
// Copy the gun to the simulated scene
ghostObj = Instantiate(gun.gameObject, gun.transform.position, gun.transform.rotation);
ghostObj.GetComponent<SpriteRenderer>().enabled = false;
SceneManager.MoveGameObjectToScene(ghostObj, simulationScene);
// Copy all the bricks to the simulated scene. These are stored under a parent Game Object that
// is attached in the editor
foreach (Transform obj in bricks.transform)
{
ghostObj = Instantiate(obj.gameObject, obj.position, obj.rotation);
ghostObj.GetComponent<SpriteRenderer>().enabled = false;
SceneManager.MoveGameObjectToScene(ghostObj, simulationScene);
}
// Copy the top, left, and right walls to the simulated scene. These are invisible and don't have sprites.
// These are stored under a parent Game Object that is attached in the editor
foreach (Transform obj in walls.transform)
{
ghostObj = Instantiate(obj.gameObject, obj.position, obj.rotation);
SceneManager.MoveGameObjectToScene(ghostObj, simulationScene);
}
} // CreatePhysicsScene
private void DrawTrajectory()
{
// Get the starting Screen position of the gun from the World position
gunPosScreenV3 = cam.WorldToScreenPoint(gun.transform.position);
gunPosScreenV3.z = 1;
// Get position of mouse in screen units
aimPointScreenV3 = Input.mousePosition;
// Get the position of the mouse in world units for aiming
aimPointWorldV3 = cam.ScreenToWorldPoint(aimPointScreenV3);
aimPointWorldV3.z = 1;
// Calculate the normalized direction of the aim point compared to the gun
aimDirectionV3 = (aimPointScreenV3 - gunPosScreenV3).normalized;
Physics2D.simulationMode = SimulationMode2D.Script;
// Instantiate the ball prefab for the simulation
ghostObj = Instantiate(ballPrefab, gun.transform.position, Quaternion.identity);
// Assign the ball's velocity
ballDirection = new Vector2(aimDirectionV3.x, aimDirectionV3.y);
ballVelocity = ballDirection * 20f;
ghostObj.GetComponent<Rigidbody2D>().velocity = ballVelocity;
SceneManager.MoveGameObjectToScene(ghostObj.gameObject, simulationScene);
lr.positionCount = maxPhysicsFrameIterations;
for (var i = 0; i < maxPhysicsFrameIterations; i++)
{
physicsScene.Simulate(Time.fixedDeltaTime);
//Physics2D.Simulate(Time.fixedDeltaTime);
lr.SetPosition(i, ghostObj.transform.position);
}
Destroy(ghostObj);
Physics2D.simulationMode = SimulationMode2D.Update;
} // DrawTrajectory
}
You use aimPointScreenV3 but it appears to never be initialized/calculated.
Found the answer. Just needed to add the velocity to the ball after moving it to the simulated scene.
SceneManager.MoveGameObjectToScene(ghostObj.gameObject, simulationScene);
ghostObj.GetComponent<Rigidbody2D>().velocity = ballVelocity;
I am a super newbie in Unity and am learning by making my first game. I want the camera to follow the player, but only in the X axis. I had earlier made the camera a child of the player, but that didn't work as I wanted. So I whipped up a C# script to follow the player, as given below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraFollow : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3(GameObject.Find("robot_body").transform.position.x, 0f, 0f);
}
}
However, this is showing only the blue background when run. Am I doing something wrong?
By setting your z position to 0 your camera probably ends up to close to everything in order to render it.
Try to not overwrite y and z with 0 but rather keep the current values:
// If possible rather already reference this via the Inspector!
[SerializeField] private GameObject robot;
private void Start()
{
// As fallback get it only ONCE
if(!robot) robot = GameObject.Find("robot_body");
}
void Update()
{
// get the current position
var position = transform.position;
// overwrite only the X component
position.x = robot.transform.position.x;
// assign the new position back
transform.position = position;
}
I have one problem. I want my prefabs to spawn every time my player picks them up. I did research on Google and YouTube and I tried to use the random function and instantiate. I don't know how to use them. I wrote this code I saw on YouTube and my prefab Sphere moves like 1cm to z position. I want to every time when I pick up object or my player go to spawn more of this on the z position. How do I do this?
My smaller script:
public GameObject Sphere;
public float zrange;
// Use this for initialization
void Start () {
RandomPosition();
}
void RandomPosition()
{
zrange = Random.Range(0f, 2f);
this.transform.position = new Vector3(0, 0, zrange);
}
You achieve that by not messing with the x and y values (your code sets them both to 0).
Vector3 p = transform.position;
p.z = zrange;
transform.position = p;
This assumes that your code to instantiate the object is already correctly placing the object. If not, more information is needed.
I am not new to programming, but I am new to C#. I am experienced in Python, Java, and HTML. My game is 2D I have a game where my character currently has to touch the enemy to kill it. Now I added code for shooting a bullet to kill the enemy. I also want the bullet to be shot if the spacebar is pressed. The character is supposed to a shoot bullet in either direction. I have taken my code from an example my professor gave me which was originally Javascript and I converted it to C#. Unity no longer supports Javascript. The example code he gave me was basically a rocket shooting as many bullets as I clicked (clicking the mouse shoots bullets) to eliminate an enemy, however the rocket in that example does not move. In my game, the character moves, so the bullet has to get the position of the character. What is the correct code for getting the character position and shooting a bullet correctly?
I tested my game with my current code. The bullet is being spit out of nowhere (from the bottom of my background wallpaper [smack in the middle of the bottom] to a little below the wallpaper). Not even from the character...
Also, I added the Hit class script to my Bullet category in Unity.
Complete Camera Controller (no issues here at all)
using UnityEngine;
using System.Collections;
public class CompleteCameraController : MonoBehaviour {
public GameObject player; //Public variable to store a reference to the player game object
private Vector3 offset; //Private variable to store the offset distance between the player and camera
// Use this for initialization
void Start ()
{
//Calculate and store the offset value by getting the distance between the player's position and camera's position.
offset = transform.position - player.transform.position;
}
// LateUpdate is called after Update each frame
void LateUpdate ()
{
// Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
transform.position = player.transform.position + offset;
}
}
Complete Player Control Class (If you read the comments in the code that say the "BULLET CODE", that's new code I have placed in the game for the bullets.
using UnityEngine;
using System.Collections;
//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;
public class CompletePlayerController : MonoBehaviour
{
public float speed; //Floating point variable to store the player's movement speed.
public Text countText; //Store a reference to the UI Text component which will display the number of pickups collected.
public Text winText; //Store a reference to the UI Text component which will display the 'You win' message.
private Rigidbody2D rb2d; //Store a reference to the Rigidbody2D component required to use 2D Physics.
private int count; //Integer to store the number of pickups collected so far.
Rigidbody2D bullet;
float speed2 = 30f; //BULLET CODE
// Use this for initialization
void Start()
{
//Get and store a reference to the Rigidbody2D component so that we can access it.
rb2d = GetComponent<Rigidbody2D> ();
//Initialize count to zero.
count = 0;
//Initialze winText to a blank string since we haven't won yet at beginning.
winText.text = "";
//Call our SetCountText function which will update the text with the current value for count.
SetCountText ();
}
//FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
void FixedUpdate()
{
//Store the current horizontal input in the float moveHorizontal.
float moveHorizontal = Input.GetAxis ("Horizontal");
//Store the current vertical input in the float moveVertical.
float moveVertical = Input.GetAxis ("Vertical");
Rigidbody2D bulletInstance; //BULLET CODE
//Use the two store floats to create a new Vector2 variable movement.
Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
//Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
rb2d.AddForce (movement * speed);
if(Input.GetKeyDown(KeyCode.Space)&& Hit.hit == false) //BULLET CODE IN HERE
{
// ... instantiate the bullet facing right and set it's velocity to the right.
bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,0)));
bulletInstance.velocity = new Vector2(speed2, 0);
bulletInstance.name = "Bullet";
}
}
//OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
void OnTriggerEnter2D(Collider2D other)
{
//Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
if (other.gameObject.CompareTag ("PickUp"))
{
//... then set the other object we just collided with to inactive.
other.gameObject.SetActive(false);
transform.localScale += new Vector3(0.1f, 0.1f, 0);
//Add one to the current value of our count variable.
count = count + 1;
//Update the currently displayed count by calling the SetCountText function.
SetCountText ();
}
}
//This function updates the text displaying the number of objects we've collected and displays our victory message if we've collected all of them.
void SetCountText()
{
//Set the text property of our our countText object to "Count: " followed by the number stored in our count variable.
countText.text = "Count: " + count.ToString ();
//Check if we've collected all 12 pickups. If we have...
if (count >= 12)
//... then set the text property of our winText object to "You win!"
winText.text = "You win!";
}
}
Hit code. All code in this class is made for the bullet.
using UnityEngine;
using System.Collections;
public class Hit : MonoBehaviour
{
GameObject[] gameObjects;
public static bool hit = false;
void Removal ()
{
gameObjects = GameObject.FindGameObjectsWithTag("Bullet");
for(var i= 0 ; i < gameObjects.Length ; i ++)
Destroy(gameObjects[i]);
}
void OnCollisionEnter2D ( Collision2D other )
{
if(other.gameObject.name=="Bullet")
{
Removal();
Destroy(gameObject);
hit = true;
}
}
}
I see several issues with the code you wrote. as #Kyle Delaney suggested, I'd also highly recommend you check out the Unity Learn website, and go through several tutorials before moving through. I've highlighted a few issues below that may help solve your problem, but you could really benefit from changing your approach in the first place to avoid many of these issues. See below.
In your camera controller class, why not make the offset public so you can set it yourself in the inspector>
In Player controller class:
changed:
if (Input.GetKeyDown(KeyCode.Space)) //Shoot bullet
{
// ... instantiate the bullet facing right and set it's velocity to the right.
Rigidbody2D bulletRB = Instantiate(bullet, transform.position, transform.rotation);
bulletRB.AddForce(new Vector2(speed2,0), ForceMode2D.Impulse);
}
On a click, this instantiates the bullet prefab and sets its transform to copy the position and rotation of the player. It then adds a force to it to the right. You should avoid setting the velocity manually with rigidbodies, this can cause unwanted behaviour. Use the Addforce/addTorque methods instead. The ForceMode says to ignore its mass and set its velocity.
Then delete your Hit class, and replace with this Bullet class, which you drag onto the bullet prefab. Your player shouldn't be in charge of checking for bullet hits. that's the bullet's job. The player just launches the bullets and then the bullets do what bullets do. this just checks to see if the bullet hit anything, if so it destroys it. You can make this more complicated if you want. I would recommend using layers to determine which layers the bullet checks collisions with. You probably don't want bullets destroying your terrain. and you definitely don't want bullets destroying the player itself!
public class Bullet : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
Destroy(collision.gameObject);
Destroy(this.gameObject);
}
}
Also you shouldn't need to set the name of the bullet, since your prefab bullet should already be named "bullet".
I hope this gets you started in the right direction. But based on your code, I HIGHLY recommend you work through the tutorials before continuing with any projects. The unity staff that make them are super helpful and the tutorials start off really simple but get really complicated fast, so you actually come away learning a ton!
Perhaps the problem has to do with the player's parent transform. You could try something like this to make sure the bullet has the right parent:
bulletInstance = Instantiate(bullet);
bulletInstance.transform.parent = transform.parent;
bulletInstance.transform.position = transform.position;
bulletInstance.velocity = new Vector2(speed2, 0);
bulletInstance.name = "Bullet";
If that doesn't work it may be worthwhile to check the player's Rect Transform to see where the anchors and pivot are. Perhaps the player's actual "position" coordinates aren't where you think they are.
Have you done the Space Shooter tutorial? It has a segment about shooting bullets.
I have a script that lays out prefabs, on a surface, by creating an array of vectors. Each array contain 14 vectors, which produce evenly spaced locations, on a plane.
public List<Vector3> handEastVectorPoints = new List<Vector3>();
public List<Vector3> handSouthVectorPoints = new List<Vector3>();
public List<Vector3> handNorthVectorPoints = new List<Vector3>();
public List<Vector3> handWestVectorPoints = new List<Vector3>();
Then when a prefab is instantiated, my code grabs the correct vector, from the correct array, and add the prefab, like this:
public IEnumerator addTileInHand(GameObject tile, Vector3 v, float time, Vector3 rotationVector, int pos)
{
Quaternion rotation = Quaternion.Euler(rotationVector);
GameObject newTile = Instantiate(tile, v, rotation);
tile.GetComponent<TileController>().canDraw = true;
tile.GetComponent<TileController>().gameStatus = getCurrentGameState();
tile.GetComponent<TileController>().currentTurn = sfs.MySelf.Id;
PlayersHand[pos] = newTile;
yield return new WaitForSeconds(time);
}
When this function is called, its passed a vector, which comes from the above array. The prefab is created, and added to an array of gameObjects.
What I now want to do is allow the player to drag and drop the to various "hot spots", as defined in the first set of arrays (again, their are 14 vectors) and drop them. If there is already a prefab in that position, I would want it to snap to the new position that just opened up. If the tile is dropped anywhere else, it should snap back to its original location. I also just want the object to be dragged either left or right, no need to up and down or up through the Y axis.
Can anyone point me to similar script that might help or provide assistance?
thanks
Edit: Draggable Script Got this working. You can only drag on the X axis, but for my use case, this works.
public class DraggableObject : MonoBehaviour {
private bool dragging = false;
private Vector3 screenPoint;
private Vector3 offset;
private float originalY;
void Start()
{
originalY = this.gameObject.transform.position.y;
}
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, originalY, screenPoint.z));
}
void OnMouseDrag()
{
Vector3 cursorPoint = new Vector3(Input.mousePosition.x, originalY, screenPoint.z);
Vector3 cursorPosition = Camera.main.ScreenToWorldPoint(cursorPoint) + offset;
transform.position = cursorPosition;
dragging = true;
}
void OnMouseUp()
{
dragging = false;
}
}
I have done a similar thing for my game. This is quite easy. Follow the following steps and let me know if you have any further queries:
Write a script (let's say HolderScript ) and add a boolean occupied to it. Add an OnTriggerEnter (A Monobehaviour function) to the script and update the boolean accordingly:
Case 1 - Holder is not occupied - Make boolean to true and disable Colliders if the prefab is dropped there, else do nothing.
Case 2 - Holder is occupied - if occupied prefab is removed then in OnTriggerExit function make boolean to false and enable colliders.
Write a Script (let's say DraggableObject) and set the drag and isDropped boolean accordingly and you can use Lerp function for snapping back.
Attach the holder script to the droppable area and DraggableObject script to the draggable objects.
This should solve your issue.