I'm making 2D platformer game using Unity 4.3.4 engine. I've created a simple prefab, which have two animations: "idle" and "death"(i used "animator") and script to control this animations.
And here's the problem: when i instantiating clones of this prefab, they always show "idle" animation and don't turn on "death" when needed.
pos = new Vector3 (-5, 4, 0) * TileSize;
newObject = Instantiate (Bonus, pos, Quaternion.identity) as GameObject;
But what is insteresting: i found a way to make animation work fine. Just add after instantiation one string like this:
newObject.animation["boxNew"].speed=1;
or this(or any string that trying to operate with "animaton"):
newObject.animation.enabled=true;
Of course i get exception at this string: "MissingComponentException: There is no 'Animation' attached to the "BonusBlock(Clone)" game object" . This is true, i really don't have Animation component, i have Animator. But why everything is working this way? Can anyone explain this?
The animator is really only used if your going full blast with the new mecanim/state flow animator, what you prolly want to do for a simple example would be to add a Animation (not animator) component to your prefab, and assign your 2 animations to the animations list in the inspector for the said animation component. Afterwards on the object you could use newObject.animation.Play("death"); to play the death animation when you want it to trigger. or use something like newObject.animation.CrossFade("death"); for a blended animation.
Found here -> http://docs.unity3d.com/Documentation/ScriptReference/Animation.html
Unity Technologies gave the answer: Before deactivating, use a default state to reset the gameObject. Discussion on Unity3d Forum
If you can read chinese, click here
Related
So, I’m trying to make an FPS character crouch. I started with a script to shrink the character controller. It works fine, but the cylinder that I’m using as a player doesn't change height. It clips through the floor. How can I create a script to change the cylinder's height? I haven't found documentation about this. Is there any better way to create the crouch script? Should I opt for rigidbody instead of character controller? I'm fairly new to unity and C# so your advice would help a lot.
You can keep your script with the character controller, but changing also the cylinder collider.
For example, you could:
Collider coll;
And in the Start() function:
coll = this.gameObject.GetComponent<CylinderCollider>();
Then when you crouch you can easily
coll.Height = 5f;
coll.y = 32f;
coll.isTrigger = false;
Basically, you can play with the variables you see in the inspector and use what fits better
I would like to use a characters tongue so instead of shooting a bullet, it goes toward the enemy, licks it, and comes back. I got this wording from this question: Unity shooting with Tongue 2d game (hasn't been answered and is 4+ years old). The only difference is my character moves.
I have this code from looking at a shooting tutorial so when you click the tongue prefab generates and is at the correct angle. I need it to grow on click and shrink back.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineController : MonoBehaviour
{
public GameObject player;
private Vector3 target;
public GameObject crosshairs;
public GameObject tonguePrefab;
// Start is called before the first frame update
void Start()
{
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
crosshairs.transform.position = new Vector2(target.x, target.y);
Vector3 difference = target - player.transform.position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
if (Input.GetMouseButtonDown(0))
{
shootTongue(rotationZ);
}
}
IEnumerator shootTongue(float rotationZ)
{
GameObject t = Instantiate(tonguePrefab) as GameObject;
t.transform.position = new Vector2(target.x, target.y);
t.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
yield return new WaitForSeconds(2000);
t.SetActive(false);
}
}
I was also trying to make it disappear after whatever time and with that it doesn't work at all?
If the prefab is just a line with a simple texture I suggest using a line renderer:
Create an empty transform that starts on the mouth and then it move untill it reaches the crosshair. The movement is done using Vector2.MoveTowards.
Your tongue will no be a line renderer component. This line renderer will have 2 points, the start which is static, and the end which you have to update on the Update() for example, to correspond to the positions of the empty transform in item 1.
If you really wish to expand a tongue gameobject instead, then you are going to need a bit of math, this answer has what you need but in 3D:
https://answers.unity.com/questions/473076/scaling-in-the-forward-direction.html
1) I suggest creating sprite/sprite sheet animations with Mecanim or relatively new Skeletal Animation with Anima2D. With these systems you can create nice animations, transitions, even animate the sphere collider to trigger collisions and actions, change active state of your objects, etc. and control the animation with very little code. This way you can get best effects in my opinion.
As tongue is not a bullet... :) You only need one. I don't think you want to Instantiate/Create prefabs every time you press the lick button. Instead you should just turn your tongue object on/off (gameObject.SetActive). You can also change your object active state within the animation. So if you don't know how to code it you can do most of it in the Animation window and use very simple code to play the animation when you press the lick button. Whenever a sphere collider touches something you can tell the Animator Controller to play a 'roll back' animation and it will transition nicely to the start position.
There are many tutorials about Mecanim, Animations, 2D Animations, Anima2D, Animator Controller out there.
2) If you need very good control over the tongue you could create a custom mesh and control it via script but this is far more difficult.
3) The reason why your object is not turning off is probably because you wrote WaitForSeconds(2000) so it will turn off after 2000 seconds - more than half an hour. You should also call it with StartCoroutine(shootTongue()) as it is a Coroutine. Again if you want to turn off the object don't create new ones every time. If you want to keep creating new objects you should Destroy the objects instead. Otherwise you will end up with a lot of deactivated tongues in your scene and I don't think you needs that many tongues.
I'm learning unity3d and c# right now with c++ and c knowledge. However, I'm confused with this line of code.
private Gameobject cubePrelab;
This is a simple line of code which "defines the object that we want to spawn" according to the lecturer.
Then he immediately do things like:
Instantiate(cubePreLab, ...,...)
which clones the object according to the documentation online.
I'm confused about the first line of code which it seems like we are just defining an object without actually initializing it. However, the result is with these two line of code, we can actually create a box on the screen but I'm confused why it is a box instead of maybe a trangle.
I suggest you read about Unity Prefabs
Since you're new to Unity, I assume you've started off by putting a few objects -- such as a cube -- into your scene right? The Unity Editor makes it easy to put objects into your scene while you're designing your game, but what if you wanted to dynamically add objects into your scene while you're playing your game?
For example, imagine that you created a scene that has a cannon in it, and every time the player hits the Space key, you want to fire a cannonball. When you create your Scene in the Unity editor, you put your cannon in your scene, but how do you add cannonballs while you're playing the game?
You could have a bunch of code that creates a cannonball from scratch every time you fire one, but that's a very time consuming and error-prone way of doing it. This is where prefabs come in. A prefab is like a blueprint for an object that you're going to add to your scene later. So a cannonball prefab would be an object that you design in the Unity Editor just like any other Unity object that you're adding to your scene. You could assign its size, its material, its color, its attack power, and so on through the Unity Editor (no code needed).
First you would create a prefab in the Unity Editor for your cannonball.
After you create a cannonball prefab, you would add a property on your Cannon class such as public GameObject cannonballPrefab, and you'd drag your cannonball prefab from the Unity editor into the "Cannonball Prefab" property of the Cannonball component on your cannon object in the Unity Inspector. So if you only look at the C# code, it looks like the cannonballPrefab field is never getting initialized. However, you are initializing it by dragging a prefab into it in the Unity Editor. To reference your initial question, this is also how Unity knows to create a box and not a triangle in your example. Unity will create an instance of whatever your prefab is.
Then within your Cannon code, you can instantiate an instance of your cannonballPrefab while you're playing the game each time you want to add a cannonball into your scene.
Now when you call Instantiate(cannonballPrefab... Unity adds an instance of your cannonball into your scene. Then you'd probably do some additional initialization by assigning it an initial position, an initial speed, an initial direction, and so on.
Also, like Pac0 said, the tutorial probably has public GameObject cubePrefab (not private) so that you can drag a reference into it from the Unity Editor. Alternatively you could keep it private and add the [SerializeField] attribute to it like below. Unity won't let you assign a private field from the editor unless it has the [SerializeField] attribute on it.
[SerializeField]
private GameObject cubePrefab;
I want an enemy to look at the player when he shoots him, I call this function from an animation event:
public void ShootPlayer
{
thisTr.LookAt(playerTr);
thisTr.rotation = Quaternion.Euler(0, thisTr.rotation.eulerAngles.y, 0);
GameObject newArrow = Instantiate(straightFlightArrow, shootPoint.position, transform.rotation);
em.canMove = true;
}
It does get called, but model`s rotation does not change. The weird thing is, if I invoke thisTr.LookAt(playerTr) in Start(), the model will rotate accordingly during the shoot animation. Also, if I rotate the model from another script the same way before the shoot animation starts it will work as well.
So for some reason trying to rotate the model specifically from the animation event does not work for me. I have tried checking constraints on and off, applied and disabled root motion, but there is no effect. I am sure that there is some obvious mistake that I make, but I just can`t figure it out.
Properties that are being animated (i.e. inhibited by the animation engine) cannot be set from code. There's a workaround for it, but it's ugly - you need to do your update in LateUpdate() (so it's after the animation engine does it's transformations) and you have to keep track of the updated value, overwriting it each and every frame (because otherwise the engine will overwrite your next frame with what it had calculated).
Other workarounds involve wrapping GameObjects in empty GameObjects, i.e. my animator animated an object's position, which I wanted to change in code as well, so my structure was:
animatedContainer
|- actualObjectAlsoAnimatedFromCode
As far as I know this also applies to properties which are inhibited at some point, but not necessarily changed during current animation (and I think this is the issue your case is facing).
I'm pretty new to Unity so please bear with me.
What I want to do:
I want my simple game object to have a linear speed on Z axis (white path on the screenshot) and perform a simple animation while this object is moving
So I have attached rigidbody to my green game object and attach a script to it and get the required component and set velocity to 10f.
myRigidBody = GetComponent<Rigidbody> ();
myRigidBody.velocity = new Vector3 (0,0,10f);
This works and the object starts moving when I hit "play" in Unity editor.
The problem:
If "Animator" component on this game object is checked, the player won't move (but it will perform animation). When I uncheck this component the game object will start to move.
In the animation itself, I'm changing the position of game object (Y axis - jump), and rotation (will flip).
The question:
Why my game object won't move (even that I've given it a linear velocity), when the animator component is checked (in action)?
I want this game object to be moving and on click perform an animation.
This is basically it. Any help highly appreciated.
EDIT: Animation values:
You can overcome the fact that Unity overrides the Rigidbody when an Animator is attached by creating a new empty GameObject and making it the parent of the existing (animating) GameObject.
I found this information on the Unity forum.