• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By Runemark Studio
      Dark Fantasy Environment and Props





    • By bowcox
      Hi guys! 
      I have created a Pong game that has an AI that is almost beatable, changing the speed of the AI can make it ridiculously easy or hard depending on the way you go about it. 
       
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class ComputerMovement : MonoBehaviour { private float speed; private float reAdjustSpeed = 1f; private Rigidbody2D computer2d; public static bool isTwoPlayer; GameObject theBall; Rigidbody2D rb2d; void Start() { computer2d = GetComponent<Rigidbody2D> (); } void FixedUpdate() { if (isTwoPlayer == true) { speed = 5f; if (Input.GetKey (KeyCode.W)) { computer2d.position += Vector2.up * speed * Time.deltaTime; } if (Input.GetKey (KeyCode.S)) { computer2d.position += Vector2.down * speed * Time.deltaTime; } } if (isTwoPlayer == false) { speed = 3f; if (theBall == null) { theBall = GameObject.FindGameObjectWithTag ("Ball"); } rb2d = theBall.GetComponent<Rigidbody2D> (); //Is the ball going left or right if (rb2d.velocity.x > 0) { if (rb2d.velocity.y > 0) { if (rb2d.position.y > computer2d.position.y) { MoveUp (); } if (rb2d.position.y < computer2d.position.y) { MoveDown (); } } if (rb2d.velocity.y < 0) { if (rb2d.position.y > computer2d.position.y) { MoveUp (); } if (rb2d.position.y < computer2d.position.y) { MoveDown (); } } } //Whilst it's not moving at the paddle, let it gain a slight reset by moving with the ball at a slower pace. if (rb2d.velocity.x < 0) { if (computer2d.position.y < 0) { computer2d.position += Vector2.up * reAdjustSpeed * Time.deltaTime; } if (computer2d.position.y > 0) { computer2d.position += Vector2.down * reAdjustSpeed * Time.deltaTime; } } } } void MoveDown() { if (Mathf.Abs(rb2d.velocity.y) > speed) { computer2d.position += Vector2.down * speed * Time.deltaTime; } else { computer2d.position += Vector2.down * speed * Time.deltaTime; } } void MoveUp() { if (Mathf.Abs (rb2d.velocity.y) > speed) { computer2d.position += Vector2.up * speed * Time.deltaTime; } else { computer2d.position += Vector2.up * speed * Time.deltaTime; } } }  
      I have looked up several posts across many different forums in order to create a much better AI. Most of the posts recommend that I use Raycasts to find out exactly where the ball might hit the paddle. I have looked up how to use them and I'm just completely lost, do raycasts consider collisions and go on infinitely or once they hit a wall, that's where it'll end up? Would anyone be able to help me understand raycasts a little better? 
      If you have another solution that enables me to calculate exactly where the ball will end up on the opponents side, I am more than willing to hear it
      Thanks again if you read this!
    • By eldwin11929
      We're looking for a Unity (C#) Programmer for our 2D Project. We're looking for a new lead programmer to continue with an existing project.
       
      Project is an open-world RTS, and is very close to a prototyping (playable) phase. Our existing lead, unfortunately, has no more time for the project, and thus we are in search of a new one who is interested.
       
      Game is purely fantasy based, and we'll be able to give you much more detailed info about the project as we begin to work you into it.
       
      You'll be working with our junior developer, who has been here since the beginning.
       
      Primary skills needed are just being able to work within Unity. But skills within XML are also a plus.
       
      Our list of major goals we'd need you to do is minimal, yet still fairly extensive:
      -Edit our current Pathfinding system to account for a few extra features.
      -Setup our global map system. You’ll be working off an existing random node-map web generator and existing random map generation system and essentially linking the two together. This includes handling random spawns (which has already been semi-setup) unique to each node’s respective map.
      -Further implementation of an existing random spawning algorithm (used to spawn things like enemies randomly across the Map).
      -Making sure to Save and Record all respective aspects of what was mentioned above.
      -Handling our XML database- database is created, but we’ll need to be integrating it. This includes all various things from units to abilities and so forth. Will also need to handle implementing an object’s unique attributes we cannot take care of within XML.
      -Various Content Implementation (to be done once our XML has been integrated).
      -Various Saving and Recording of all respective aspects of the database info mentioned above.
      -Various Performance Enhancements.
      -Potential for various misc things, such as further UI work.
      -Setting up a Menu system.
       
      We have a considerable amount of things done already- however I must warn ahead of time we have quite a bit of unclean code, which may be fairly overwhelming for a new developer on the project.
       
      Let me know your rates per hour, and we'll see if we can work out a good deal between both of us. Royalties are also included.
       
      If interested, send an email to: eldwin11929@yahoo.com
       
      Thanks!
    • By jhocking
      My bestselling and highly recommended Unity book has been fully revised! Unity in Action, Second Edition teaches you to write and deploy games with the Unity game development platform. You'll master the Unity toolset from the ground up, adding the skills you need to go from application coder to game developer.

      Foreword by Jesse Schell, author of The Art of Game Design

      Don't take my word for it being good, look at the sky-high ratings on GoodReads.

      You can order the ebook directly from the publisher's site, or order the book on Amazon to get both the physical book and a coupon to download the ebook!
    • By ThunderTwonk
      Hello everyone, I am working on a game idea and since I am still in the process of learning C# and the features available in unity I was hoping some of you might be able to offer me a little insight on things in general for getting started.
      I guess the basic components of what I'm wanting to create would be a Multi-levels management/city builder/rpg.
      The goal is to provide a framework for players to interact with, build in and affect the world both from a 3rd person action RPG as well as a zoomed out 4x style view (This would be something unlocked through gameplay)
       
      As for my questions go I was wondering if anyone had resources that could help me learn.  I've been on youtube as well as enrolled in an online course for basic unity and C# and will continue those but if anyone has any words of advice, a place that has good information and tutorials etc.
       
      Thanks for your time.
  • Advertisement
  • Advertisement
Sign in to follow this  

Unity Unity Animation Help

This topic is 1001 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello,

 

I need some help with playing an animation after a ball has hit a target. The code is in C#. I've tried playing the animation by first declaring it. I've also tried to play it by using the getComponent method. When the ball hits the target, the animation dosen't play. It's just a still frame. Any help is greatly appericated. I can provide more code or info if it is needed.

Animation LightWoman;

void OnCollisionEnter(Collision col) {
      if(col.gameObject.CompareTag("ball") && col.gameObject.CompareTag("Doofus1"))
			{
				this.GetComponent<Animation>().Play("DoofusAni");
			}

    	else if(col.gameObject.CompareTag("ball") && col.gameObject.CompareTag("lightwoman1"))
			{
				LightWoman.Play("LightWomanAni");
			}
}
Edited by LeftyGuitar

Share this post


Link to post
Share on other sites
Advertisement

First utilize mechanim. Create an empty animation call it do nothing this is your default animation. Then add your ball animation to mechanims animation window and create a transition to the new animation from DoNothing. Add a trigger param that will cause this DoNothing to transition to the other animation. I used lots of key words for you to look at the documentation and/or find exactly how to do that. You could even create a int param and give this animation the value of 1 so when you set this param to 1 the animation plays.

 

Here is an example usage of it http://docs.unity3d.com/Manual/AnimationParameters.html

 

I hope that helps... If I was at my dev station I would write up an exact example but I am sadly not.

Share this post


Link to post
Share on other sites

I probably should have explained it more. I'm just trying to play an animation clip through code, once the ball hits the target, the body image should animate. I already made the clips, they're just not playing even though I have them set to play.

Share this post


Link to post
Share on other sites

Your if statements seem incorrect. Take a look at the first one; it is only true if it has two tags: "ball" and "Doofus1". However, a GameObject can only have 1 tag, not multiple, so this statement will never be true. The same goes for the second if statement.

 

If fixing that part doesn't solve the entire problem, you might want to double check a few of the following things:

 

1. An obvious one: are there any errors/exceptions?

2. Do you have the correct tag assigned to the GameObject you are testing collision with? (i.e. is there really an object with that tag colliding in the test you have?).

Share this post


Link to post
Share on other sites
using UnityEngine;
using System.Collections;

public class Target : MonoBehaviour {

	// Use this for initialization

	Animation DarkWomanSuitAni;
    GameObject womansuit;
	void Start () {
	}



	// Update is called once per frame
	void Update () {
		if(GameObject.FindGameObjectWithTag("lightwoman1"))
		{
			gameObject.SetActive(true);
		}
	}



	void OnCollisionEnter(Collision col) {


		if (col.gameObject.CompareTag ("ball")) {

			// SEND MESSAGE HERE
			Debug.Log("TARGET HIT: trigger animation and poin increase here");
			this.GetComponent<Animation>().Play("target_hit");
			//this.GetComponent<Player>().dunks++;

			//this.GetComponent<Animation>().Play("SeatFlip");
			//col.gameObject.GetComponent<Animation>().Play("LightWomanAni");

			DarkWomanSuitAni.Play("DarkWomanSuitAni");
	
			 
			 //col.gameObject.GetComponent<Animation>().Play("LightWomanAni");
			 SoundManager.Instance.PlaySound("splash");

			// ignores collision with ball after being hit once 
			// (to prevent multiple hits from the same ball) 
			Physics.IgnoreCollision(this.GetComponent<Collider>(), col.collider);
		}
}

Ok, so what I want to do is play the animation after you hit the target with the ball. When I try to hit the target, it says onTrigger event not found. Or object reference not set to an instance of object.

Share this post


Link to post
Share on other sites

Does it switch between those errors or are you only getting "object reference not set to an instance of an object" (better known as a nullreference exception)? 

 

If the latter, try to see where it's going wrong by looking at the line number the error is indicating in the Unity log. You can also double click it to make it select the line number of where the exception occurred in your IDE immediately.

The error is telling you that you are trying to do something with an object that (no longer) exists (the object is referencing 'null')! It being null could be the result of the of calling GetComponent without the component being found and thus returning null instead.  Another possibility is that you haven't assigned a reference to the "DarkWomanSuitAni" component in the editor, causing it to be null as well.

Anyway, at this point it could be anything really, we have to guess and it's much easier and quicker for you to try and find the problem yourself from there on smile.png. (though you can of course come back if you have any additional questions.)

 

If you are also getting an error occasionally that says something like the 'onTrigger event not found' as you mentioned, we will need some more info/code, as I don't recall Unity ever giving such an error from itself*.

 

*(sounds like a custom message requiring a receiver, while not having any)

Share this post


Link to post
Share on other sites

NullReferenceException
UnityEngine.Animation.Play (System.String animation) (at C:/buildslave/unity/build/artifacts/generated/common/modules/AnimationsBindings.gen.cs:612)
Target.OnCollisionEnter (UnityEngine.Collision col) (at Assets/Scripts/Caleb/Target.cs:39)
 

This is the error I'm getting and here is my updated code.

using UnityEngine;
using System.Collections;

public class Target : MonoBehaviour {

	// Use this for initialization

	Animation DarkWomanSuitAni;
    GameObject womansuit;
	void Start () {
		DarkWomanSuitAni = new Animation();
	}



	// Update is called once per frame
	void Update () {
		if(GameObject.FindGameObjectWithTag("lightwoman1"))
		{
			gameObject.SetActive(true);
		}
	}



	void OnCollisionEnter(Collision col) {


		if (col.gameObject.CompareTag ("ball")) {

			// SEND MESSAGE HERE
			Debug.Log("TARGET HIT: trigger animation and poin increase here");
			this.GetComponent<Animation>().Play("target_hit");
			//this.GetComponent<Player>().dunks++;

			//this.GetComponent<Animation>().Play("SeatFlip");
			//col.gameObject.GetComponent<Animation>().Play("LightWomanAni");
	
			DarkWomanSuitAni.Play("DarkWomanSuitAni");
			 
			 //col.gameObject.GetComponent<Animation>().Play("LightWomanAni");
			 SoundManager.Instance.PlaySound("splash");

			// ignores collision with ball after being hit once 
			// (to prevent multiple hits from the same ball) 
			Physics.IgnoreCollision(this.GetComponent<Collider>(), col.collider);
		}
}

Share this post


Link to post
Share on other sites

It is odd that you are defining a animation object in the start yet in the collision code that variable is null.  I bet if you do a check on the DarkWomanSuitAni object it will return as a null object meaning it didn't get instantiated.  Have you verified if the Start method is being called on the game object?  Try logging something to the dubug console in your start method to see if that is being executed.  If this is not then your game object isn't getting istantiated fully in Unity.

 

Any more details you can provide might be helpful for us in diagnosing this issue.  But as it stands all we can do is generically suggest places to look for problems and take a stab in the dark to help you.

Edited by lede

Share this post


Link to post
Share on other sites

In start, you create a new animation, rather than referencing the one that is currently on the GameObject. What you want to do is make the variable available for assignment in the editor or use the component to get the already existing animation.

 

Making it possible to assign (drag in) a reference to a component in the editor can be done by using the SerializeField attribute like so:

[SerializeField]
private Animation animation;

(you can omit the 'private', though)

 

Currently it's most likely throwing the exception because the new animation component you create in the Start method isn't the one with the animation clip you are looking for. You are now trying to play the animation "DarkWomanSuitAni" on an animation component that doesn't have this particular animation clip (in fact, it has no animation clips at all!).

Share this post


Link to post
Share on other sites

NullReferenceException
UnityEngine.Animation.Play (System.String animation) (at C:/buildslave/unity/build/artifacts/generated/common/modules/AnimationsBindings.gen.cs:612)
Target.OnCollisionEnter (UnityEngine.Collision col) (at Assets/Scripts/Caleb/Target.cs:40)
 

I'm getting this error now. I tried adding in the SerializeField command.

using UnityEngine;
using System.Collections;

public class Target : MonoBehaviour {

	// Use this for initialization

	[SerializeField]
	Animation DarkWomanSuitAni;
    GameObject womansuit;
	void Start () {
		DarkWomanSuitAni = new Animation();
	}



	// Update is called once per frame
	void Update () {
		if(GameObject.FindGameObjectWithTag("lightwoman1"))
		{
			gameObject.SetActive(true);
		}
	}



	void OnCollisionEnter(Collision col) {


		if (col.gameObject.CompareTag ("ball")) {

			// SEND MESSAGE HERE
			Debug.Log("TARGET HIT: trigger animation and poin increase here");
			this.GetComponent<Animation>().Play("target_hit");
			//this.GetComponent<Player>().dunks++;

			//this.GetComponent<Animation>().Play("SeatFlip");
			//col.gameObject.GetComponent<Animation>().Play("LightWomanAni");
	
			DarkWomanSuitAni.Play("DarkWomanSuitAni");
			 
			 //col.gameObject.GetComponent<Animation>().Play("LightWomanAni");
			 SoundManager.Instance.PlaySound("splash");

			// ignores collision with ball after being hit once 
			// (to prevent multiple hits from the same ball) 
			Physics.IgnoreCollision(this.GetComponent<Collider>(), col.collider);
		}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement