Audio Source in Unity ArgumentNullException - c#

So I want to play an audio source when a collision trigger happens, but unity throws this exception:
ArgumentNullException: Value cannot be null. Parameter name: source
UnityEngine.AudioSource.Play () (at
<8e2857b79be4468ca1c28dda75978191>:0) PlanetMovement.OnTriggerEnter2D
(UnityEngine.Collider2D collision) (at
Assets/Scripts/PlanetMovement.cs:47)
This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlanetMovement : MonoBehaviour
{
bool moveAllowed;
Collider2D col;
public float moveSpeed;
public GameObject restartPanel;
private AudioSource source;
// Start is called before the first frame update
void Start()
{
source = GetComponent<AudioSource>();
col = GetComponent<Collider2D>();
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
transform.position = Vector2.MoveTowards(transform.position, touchPosition, moveSpeed * Time.deltaTime);
}
}
public void GameOver()
{
Invoke("Delay", 1.5f);
}
public void Delay()
{
restartPanel.SetActive(true);
Time.timeScale = 0;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Asteroid")
{
source.Play();
GameOver();
Debug.Log("Hit");
}
}
}
The collision trigger works perfectly without the audio source. I don't know what's going on. The asteroids are a prefab spawned dynamically, if that's useful info.
Thank you.

My bad. Instead of creating an AudioSource component on the planet, I created a new AudioSource GameObject and then put it as a child of the planet. It's fixed
Sorry.

Related

Unity2d: the player stop moving when I add an animation

I have a problem in unity , the player mouvement is going good until I add an animation the player stop moving even if I press the keyboard keys,when I remove the animator compenent the player move normaly without problems !
I tried separate the animation script from the movement script and still theame problem , I don't think that the problem is comming from the code
playerAnimation code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerAnim : MonoBehaviour
{
Animator anim;
Rigidbody2D rb;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
void FixedUpdate()
{
if (rb.velocity.x == 0)
anim.SetBool("isRunning", false);
else
anim.SetBool("isRunning", true);
if (rb.velocity.y > 0)
anim.SetBool("isJumping", true);
else
anim.SetBool("isJumping", false);
}
}
playerMovement script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerControl : MonoBehaviour
{
Rigidbody2D rb;
private float horizontal;
public float runSpeed;
public float jumpPower;
public bool inTheGround;
private SpriteRenderer sp;
Animator anim;
// Start is called before the first frame update
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
sp = gameObject.GetComponent<SpriteRenderer>();
anim = gameObject.GetComponent<Animator>();
}
private void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
}
private void FixedUpdate()
{
rb.velocity = new Vector2(horizontal * runSpeed,
rb.velocity.y);
if (Input.GetButton("Jump")&& inTheGround)
{
rb.velocity = new Vector2(rb.velocity.x,jumpPower);
}
flipping();
Debug.Log(rb.velocity.x);
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("ground"))
inTheGround = true;
}
private void OnCollisionExit2D(Collision2D other)
{
if
(other.gameObject.CompareTag("ground")&&rb.velocity.y>0.1)
inTheGround = false;
}
void flipping()
{
if (Input.GetKey(KeyCode.RightArrow))
sp.flipX = false;
if (Input.GetKey(KeyCode.LeftArrow))
sp.flipX = true;
}
}
Check if Apply Root Motion on Animator Component is set to false. This setting can overwrite your changes of the object's position over time. if not - can you please provide more information, perfectly a screenshot of your player components, and Animator Controller.

Why can I not collect coins and I get an error message

I'm new to unity and C# as well but I do have a small understanding of it because I've learnt python. At the moment I've run into an error, I'm trying to make a coin collection system and also the players movement in one script simply because it seems neater that way and easier to play audio.
The error comes up on this line, [SerializeField] private Transform groundcheck = null; (it's used so the player can jump over and over). I have a theory that maybe I just need to change the collision value, but other then no clue what I need to do to change this error.
Full Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private Transform groundcheck = null;
private bool jumpkeywaspressed;
private float horizontalInput;
private Rigidbody rigibodycomponent;
public AudioSource coincollect;
// Start is called before the first frame update
void Start()
{
rigibodycomponent = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
jumpkeywaspressed = true;
horizontalInput = Input.GetAxis("Horizontal");
}
private void FixedUpdate()
{
rigibodycomponent.velocity = new Vector3(horizontalInput * 3, rigibodycomponent.velocity.y,0);
if (Physics.OverlapSphere(groundcheck.position, 0.1f).Length == 1)
{
return;
}
if (jumpkeywaspressed)
{
rigibodycomponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
jumpkeywaspressed = false;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == 6)
{
coincollect.Play();
ScoreManager.sManger.IncreaseScore(1);
Destroy(other.gameObject);
}
}
}
I also have another script which is used to increase the score but I don't think it effects my error.

My animation is not returning to idle but goes from idle to run animation and then never returns

I need help my animation is not returning back to idle this is for my enemy. I have the transitions set up in the animator and i have a bool parameter for true and false and no I don't want to use unity built in ai thing.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossMovement : MonoBehaviour
{
public Animator anim;
public float distance;
public Transform target;
public float speed = 4f;
Rigidbody rig;
// Start is called before the first frame update
void Start()
{
rig = GetComponent<Rigidbody>();
}
private void Update()
{
whento();
transform.LookAt(target);
}
// Update is called once per frame
void followPlayer()
{
Vector3 pos = Vector3.MoveTowards(transform.position, target.position, speed * Time.fixedDeltaTime);
rig.MovePosition(pos);
transform.LookAt(target);
}
void whento()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, distance))
{
if (hit.transform.tag == "Player")
{
followPlayer();
anim.SetBool("isMoving", true);
}
else if (hit.transform.tag != "Player")
{
anim.SetBool("isMoving", false);
}
}
}
}
Try replacing the last else if Statement to just an else Statement. This way your code works regardless if you hit something or not.

Having problems with "OnCollisionEnter2D" in Unity2D

I'm using this code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CollisionPlayer : MonoBehaviour
{
public bool alreadyDied = false;
public GameObject player;
public float timeDeath;
public ParticleSystem particles;
public GameObject explosionGO;
private SpriteRenderer sr;
private BoxCollider2D bc;
private PlayerController walkScript;
void Start()
{
sr = GetComponent<SpriteRenderer>();
bc = GetComponent<BoxCollider2D>();
walkScript = GetComponent<PlayerController>();
}
void OnCollisionEnter2D (Collision2D collide)
{
if (collide.gameObject.CompareTag("Dead"))
{
Instantiate(particles, player.transform.position, Quaternion.identity);
Instantiate(explosionGO, player.transform.position, Quaternion.identity);
CinemachineShake.Instance.ShakeCamera(30f, .1f);
alreadyDied = true;
}
}
void Update()
{
if(alreadyDied == true)
{
timeDeath -= Time.deltaTime;
sr.enabled = false;
bc.enabled = false;
walkScript.enabled = false;
}
if(timeDeath <= 0)
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}
This is the bullet's code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeftBulletScript : MonoBehaviour
{
// Start is called before the first frame update
public float speed;
public float destructionLeftTime;
public ParticleSystem particles;
private GameObject thisGameObject;
void Start()
{
thisGameObject = this.gameObject;
Destroy(gameObject, destructionLeftTime);
}
void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
if(destructionLeftTime > 0.05f)
{
destructionLeftTime -= Time.deltaTime;
}
else
{
Instantiate(particles, thisGameObject.transform.position, Quaternion.identity);
}
}
}
This code should spawn some particles and a sound effect when the player gets hit by something with tag "Dead". But that does not happen. I have a box collider 2D on both the bullet (that should kill me) and the player. My Rigidbody2D is dynamic on the player with z freezed. The bullet does not have a rigidbody. I made sure that the bullet actually has the tag "Dead", spelled the exact same way as the way I wrote on the script. The weirdest thing is that I used this code on another game and nothing changed (just the name of a script). Both the player and the bullet are on the same layer. Anyone could tell me what could have happened?

unity3D, enemy following issue

I'm trying to make enemies follow my player when the player enters the radius area of an enemy, but make the enemy stop following when my bullet hits object or enters radiusArea.
See my gif for more detail:
Gif
script:
using UnityEngine;
using System.Collections;
public class FlyEnemyMove : MonoBehaviour
{
public float moveSpeed;
public float playerRange;
public LayerMask playerLayer;
public bool playerInRange;
PlayerController thePlayer;
// Use this for initialization
void Start()
{
thePlayer = FindObjectOfType<PlayerController>();
}
// Update is called once per frame
void Update()
{
flip();
playerInRange = Physics2D.OverlapCircle(transform.position, playerRange, playerLayer);
if (playerInRange)
{
transform.position = Vector3.MoveTowards(transform.position, thePlayer.transform.position, moveSpeed * Time.deltaTime);
//Debug.Log(transform.position.y);
}
//Debug.Log(playerInRange);
}
void OnDrawGizmosSelected()
{
Gizmos.DrawWireSphere(transform.position, playerRange);
}
void flip()
{
if (thePlayer.transform.position.x < transform.position.x)
{
transform.localScale = new Vector3(0.2377247f, 0.2377247f, 0.2377247f);
}
else
{
transform.localScale = new Vector3(-0.2377247f, 0.2377247f, 0.2377247f);
}
}
}
I hope someone can help me :(
Physics2D.OverlapCircle detects only the collider with the lowest z value (if multiple are in range). So you either need to change the z values so the player has the lowest or you need to work with Physics2D.OverlapCircleAll and check the list to find the player. Or you could change your layers so only the player itself is on that specific layer you feed into the overlap test.

Categories