I have this code:
public class BasicMovement : MonoBehaviour {
private Animation anim;
public float jumpPower = 15f;
private Rigidbody2D rb;
bool canJump;
// Use this for initialization
void Start () {
anim = this.gameObject.GetComponent<Animation>();
anim.Play("Run");
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
// FIX LATER for collider, not position
if (rb.position.y <= -2.95) // this is line 23
{
canJump = true;
}
if (canJump)
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = new Vector2(rb.velocity.x, jumpPower);
canJump = false;
}
}
}
}
I get this error:
Object reference not set to instance of object: 23
For some reason, if I take anim.Play("Run"); out, then there is no error at all.
Also, I made the RUN and JUMP animations to the gameObject this script is assigned to.
The GameObject which has this script doesn't have the Animation component added to it, giving you null when you're trying to fetch it with anim = this.gameObject.GetComponent<Animation>();
Make sure your Animation component is added to the GameObject and then try again!
I had to use anim = this.gameObject.GetComponent<Animator>(); instead of Animation, and it worked.
Related
I'm trying to solve an issue in Unity 2d game creation.
So, my issue is when the subject is idle, the 2d player object should be idle and when I move the character, it must animate like walking.
But in my case, the walking animation is not working but the character is moving.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField]
private float jumpmovement = 11f;
[SerializeField]
private float movement = 10f;
private float movementx;
[SerializeField]
private Rigidbody2D mybody;
private Animator anim;
[SerializeField]
private string Walk_Ani = "Player is walking";
private SpriteRenderer sr;
private void Awake()
{
mybody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
sr = GetComponent<SpriteRenderer>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Playerkeymove();
animateplayer1();
}
void Playerkeymove()
{
movementx = Input.GetAxisRaw("Horizontal");
// Debug.Log(movementx);
transform.position += new Vector3(movementx, 0f, 0f) * movement * Time.deltaTime;
// Debug.Log(transform.position);
}
void animateplayer1()
{
// anim.SetBool(Walk_Ani , true);
// we are going to the right side
if (movementx > 0)
{
anim.SetBool(Walk_Ani, true);
sr.flipX = false;
}
else if (movementx < 0)
{
// we are going to the left side
anim.SetBool(Walk_Ani, true);
sr.flipX = true;
}
else
{
anim.SetBool(Walk_Ani, false);
}
}
}
I can't understand, why I have a warning issue with boolean part where I guess that's where my animation takes part.
You are trying to set a boolean parameter in the Animator that doesn't exists. The code is correct. Check what name you choose for the bool parameter to active correctly the animation.
Hello I am trying to make a ragdoll player in unity 2d. All the parts of the character are held together by hinges and I'm trying to make it move. I do not want to use animations as I prefer a real ragdoll. My current movement isn't working, here is my code :)`
bool aKey = false;
float speedl = -20f;
private Rigidbody2D rb2D;
private void Start()
{
rb2D = gameObject.AddComponent<Rigidbody2D>();
bool aKey = Input.GetKey(KeyCode.A);
}
// Update is called once per frame
void Update()
{
if(aKey == true)
{
rb2D.AddForce(transform.forward * speedl);
}
}
Start function run only once so move your GetKey functions to inside of Update() function.
private void Start()
{
rb2D = gameObject.AddComponent<Rigidbody2D>();
}
void Update()
{
if(Input.GetKey(KeyCode.A))
{
rb2D.AddForce(transform.forward * speedl);
}
}
I am trying to make a script that Instantiates a ball when called. However the balls RigidBody2D and Collider2D are already in the scene upon build, prior to Instantiation. Why is this happening?
Ball Script:
public class Ball : MonoBehaviour
{
[SerializeField]
private Rigidbody2D rb;
[SerializeField]
private float speed = 10;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
Launch();
this.gameObject.name = "Ball";
BoxCollider boxCollider = gameObject.AddComponent<BoxCollider>();
Rigidbody2D gameObjectsRigidBody = this.gameObject.AddComponent<Rigidbody2D>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void Launch()
{
//code used to determine in which direction the ball should go when it spawns
float x = Random.Range(0, 2) == 0 ? -1 : 1;
float y = Random.Range(0, 2) == 0 ? -1 : 1;
rb.velocity = new Vector2(speed * x, speed * y);
}
}
Thanks in advance!
The Awake function will be called even if the program is disabled. Therefore the RigidBody2D and Collider2D were already instantiated and were not updated. You should move the code from Awake to Start and enable the script using the snippet below:
private Scriptname script;
private void Awake()
{
script = GetComponent<ScriptName>();
script.enabled = true;
}
More info on this subject here
I'm a beginner at Unity with a problem for which I've not been able to find an answer on any of the boards. Creating a very basic Unity C# script, I have the following lines of code in my Awake() function:
Assert.IsNotNull(sfxJump);
Assert.IsNotNull(sfxDeath);
Assert.IsNotNull(sfxCoin);
The third assertion "
Assert.IsNotNull(sfxCoin) throws as null, even though the coin AudioClip is set in the Inspector:
Inspector script values:
However -- and this is the part that has me baffled -- for some reason sfxCoin is not null when invoked in the same script from an OnCollisionEnter() routine
So it appears Unity does register the object with the code -- eventually -- but the assertions fail with the initial Awake(), Start(), and Update() methods.
And this only is happening with sfxCoin. sfxJump and sfxDeath do not have this issue.
Any help would be appreciated
Entire script is below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
public class Player : MonoBehaviour
{
[SerializeField] private float jumpForce = 100f;
[SerializeField] private float forwardMomentum = 5f;
[SerializeField] private AudioClip sfxJump;
[SerializeField] private AudioClip sfxDeath;
[SerializeField] private AudioClip sfxCoin;
private Animator anim;
private Rigidbody Rigidbody;
private bool jump = false;
private AudioSource audioSource;
private void Awake()
{
Assert.IsNotNull(sfxJump);
Assert.IsNotNull(sfxDeath);
Assert.IsNotNull(sfxCoin);
}
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
Rigidbody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (!GameManager.instance.GameOver() && GameManager.instance.GameStarted())
{
if (Input.GetMouseButton(0))
{
GameManager.instance.PlayerStartedGame();
anim.Play("Jump");
audioSource.PlayOneShot(sfxJump);
Rigidbody.useGravity = true;
jump = true;
}
}
}
private void FixedUpdate()
{
if (jump)
{
jump = false;
Rigidbody.velocity = new Vector2(0, 0);
Rigidbody.AddForce(new Vector2(forwardMomentum, jumpForce), ForceMode.Impulse);
}
}
private void OnCollisionEnter(Collision collision)
{
switch (collision.gameObject.tag)
{
case "obstacle":
Rigidbody.AddForce(new Vector2(-50, 20), ForceMode.Impulse);
Rigidbody.detectCollisions = false;
audioSource.PlayOneShot(sfxDeath);
GameManager.instance.PlayerCollided();
break;
case "coin":
audioSource.PlayOneShot(sfxCoin);
GameManager.instance.Score(1);
print("GOT COIN");
break;
}
}
}
sorry, I found out what the problem was.
There was a second instance of a game object that was also using the same script that did not have sfxCoin set. It was hidden under a node in the hierarchy so I didn't see it.
Like I said, I'm a beginner at this.
I imported Unity Standard Assets cross platform input successfully
In imported cross Platfrom script UnityStandardAssets.CrossCrossPlatformInput is working perfectly
but when i use it in CharacterController2D script that not respoonding
shows errors
unknown package actually namespace in C#
and in file path for standard assets is
Assets\Standard Assets\CrossPlatformInput\Scripts
and CharacterController2D path is
Assets\Scripts
following CharacterController2D script is
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement; // include so we can load new scenes
using UnityStandardAssets.CrossCrossPlatformInput; //even this line shows error
public class CharacterController2D : MonoBehaviour {
// player controls
[Range(0.0f, 10.0f)] // create a slider in the editor and set limits on moveSpeed
public float moveSpeed = 3f;
public float jumpForce = 600f;
// player health
public int playerHealth = 1;
// LayerMask to determine what is considered ground for the player
public LayerMask whatIsGround;
// Transform just below feet for checking if player is grounded
public Transform groundCheck;
// player can move?
// we want this public so other scripts can access it but we don't want to show in editor as it might confuse designer
[HideInInspector]
public bool playerCanMove = true;
// SFXs
public AudioClip coinSFX;
public AudioClip deathSFX;
public AudioClip fallSFX;
public AudioClip jumpSFX;
public AudioClip victorySFX;
// private variables below
// store references to components on the gameObject
Transform _transform;
Rigidbody2D _rigidbody;
Animator _animator;
AudioSource _audio;
// hold player motion in this timestep
float _vx;
float _vy;
// player tracking
bool facingRight = true;
bool isGrounded = false;
bool isRunning = false;
bool canDoubleJump = false;
// store the layer the player is on (setup in Awake)
int _playerLayer;
// number of layer that Platforms are on (setup in Awake)
int _platformLayer;
void Awake () {
// get a reference to the components we are going to be changing and store a reference for efficiency purposes
_transform = GetComponent<Transform> ();
_rigidbody = GetComponent<Rigidbody2D> ();
if (_rigidbody==null) // if Rigidbody is missing
Debug.LogError("Rigidbody2D component missing from this gameobject");
_animator = GetComponent<Animator>();
if (_animator==null) // if Animator is missing
Debug.LogError("Animator component missing from this gameobject");
_audio = GetComponent<AudioSource> ();
if (_audio==null) { // if AudioSource is missing
Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
// let's just add the AudioSource component dynamically
_audio = gameObject.AddComponent<AudioSource>();
}
// determine the player's specified layer
_playerLayer = this.gameObject.layer;
// determine the platform's specified layer
_platformLayer = LayerMask.NameToLayer("Platform");
}
// this is where most of the player controller magic happens each game event loop
void Update()
{
// exit update if player cannot move or game is paused
if (!playerCanMove || (Time.timeScale == 0f))
return;
// determine horizontal velocity change based on the horizontal input
_vx = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
// Determine if running based on the horizontal movement
if (_vx != 0)
{
isRunning = true;
} else {
isRunning = false;
}
// set the running animation state
_animator.SetBool("Running", isRunning);
// get the current vertical velocity from the rigidbody component
_vy = _rigidbody.velocity.y;
// Check to see if character is grounded by raycasting from the middle of the player
// down to the groundCheck position and see if collected with gameobjects on the
// whatIsGround layer
isGrounded = Physics2D.Linecast(_transform.position, groundCheck.position, whatIsGround);
///checking if can do double jump or not
if (isGrounded)
{
canDoubleJump = true;
}
// Set the grounded animation states
_animator.SetBool("Grounded", isGrounded);
if(isGrounded && CrossPlatformInputManager.GetButtonDown("Jump")) // If grounded AND jump button pressed, then allow the player to jump
{
doJump ();
}
else if(canDoubleJump && CrossPlatformInputManager.GetButtonDown("Jump"))
{
doJump ();
canDoubleJump = false; //disabling dpuble jump after single jump
}
// If the player stops jumping mid jump and player is not yet falling
// then set the vertical velocity to 0 (he will start to fall from gravity)
if(CrossPlatformInputManager.GetButtonUp("Jump") && _vy>0f)
{
_vy = 0f;
}
// Change the actual velocity on the rigidbody
_rigidbody.velocity = new Vector2(_vx * moveSpeed, _vy);
// if moving up then don't collide with platform layer
// this allows the player to jump up through things on the platform layer
// NOTE: requires the platforms to be on a layer named "Platform"
Physics2D.IgnoreLayerCollision(_playerLayer, _platformLayer, (_vy > 0.0f));
}
// Checking to see if the sprite should be flipped
// this is done in LateUpdate since the Animator may override the localScale
// this code will flip the player even if the animator is controlling scale
void LateUpdate()
{
// get the current scale
Vector3 localScale = _transform.localScale;
if (_vx > 0) // moving right so face right
{
facingRight = true;
} else if (_vx < 0) { // moving left so face left
facingRight = false;
}
// check to see if scale x is right for the player
// if not, multiple by -1 which is an easy way to flip a sprite
if (((facingRight) && (localScale.x<0)) || ((!facingRight) && (localScale.x>0))) {
localScale.x *= -1;
}
// update the scale
_transform.localScale = localScale;
}
// if the player collides with a MovingPlatform, then make it a child of that platform
// so it will go for a ride on the MovingPlatform
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag=="MovingPlatform")
{
this.transform.parent = other.transform;
}
}
// if the player exits a collision with a moving platform, then unchild it
void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag=="MovingPlatform")
{
this.transform.parent = null;
}
}
// do what needs to be done to freeze the player
void FreezeMotion() {
playerCanMove = false;
_rigidbody.isKinematic = true;
}
// do what needs to be done to unfreeze the player
void UnFreezeMotion() {
playerCanMove = true;
_rigidbody.isKinematic = false;
}
// play sound through the audiosource on the gameobject
void PlaySound(AudioClip clip)
{
_audio.PlayOneShot(clip);
}
// public function to apply damage to the player
public void ApplyDamage (int damage) {
if (playerCanMove) {
playerHealth -= damage;
if (playerHealth <= 0) { // player is now dead, so start dying
PlaySound(deathSFX);
StartCoroutine (KillPlayer ());
}
}
}
//Public Jump function
public void doJump()
{
// reset current vertical motion to 0 prior to jump
_vy = 0f;
// add a force in the up direction
_rigidbody.AddForce (new Vector2 (0, jumpForce));
// play the jump sound
PlaySound(jumpSFX);
}
//EnemyJump function
public void EnemyJump()
{
doJump ();
}
// public function to kill the player when they have a fall death
public void FallDeath () {
if (playerCanMove) {
playerHealth = 0;
PlaySound(fallSFX);
StartCoroutine (KillPlayer ());
}
}
// coroutine to kill the player
IEnumerator KillPlayer()
{
if (playerCanMove)
{
// freeze the player
FreezeMotion();
// play the death animation
_animator.SetTrigger("Death");
// After waiting tell the GameManager to reset the game
yield return new WaitForSeconds(2.0f);
if (GameManager.gm) // if the gameManager is available, tell it to reset the game
GameManager.gm.ResetGame();
else // otherwise, just reload the current level
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
public void CollectCoin(int amount) {
PlaySound(coinSFX);
if (GameManager.gm) // add the points through the game manager, if it is available
GameManager.gm.AddPoints(amount);
}
// public function on victory over the level
public void Victory() {
PlaySound(victorySFX);
FreezeMotion ();
_animator.SetTrigger("Victory");
if (GameManager.gm) // do the game manager level compete stuff, if it is available
GameManager.gm.LevelCompete();
}
// public function to respawn the player at the appropriate location
public void Respawn(Vector3 spawnloc) {
UnFreezeMotion();
playerHealth = 1;
_transform.parent = null;
_transform.position = spawnloc;
_animator.SetTrigger("Respawn");
}
}
This is first time that I have used cross platform input
so I don't even know why this error is showing
Sorry to Bother you guys.
I think i found my error in this code
actually i mistakenly write
using UnityStandardAssets.CrossCrossPlatformInput;
instead of
using UnityStandardAssets.CrossPlatformInput;
that's why it's showing error Unknown Namespace Under Standard Unity Assests
Actually I am new to Unity and also new to game development
i think that's why this problem happen
also, you need to use a compiler definition as shown, i was stuck on it for a long time, but found it written in the guidelines that come along with standard asset package..
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
// CROSS_PLATFORM_INPUT
public class Player : MonoBehaviour
{
public float speed = 6f;
Vector2 moveVelocity;
public Rigidbody2D rb;
Vector2 movement;
void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
moveVelocity = moveInput * speed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
public void Up()
{
FixedUpdate();
}
private void OnTriggerEnter2D(Collider2D target)
{
if (target.tag == "Enemy")
{
GameManager.instance.PlayerDied();
Debug.Log("ok");
}
if (target.tag == "Finish")
{
Debug.Log("ok");
GameManager.instance.PlayerWin();
}
}
}