I am working on a game, like a fire fighter, here is scenario in which player has to extinguish the fire through cloth, I had successfully made a cloth, and I am able to pick it but when I throw it, it doesn't throw, it remained there.
Here I want to throw cloth at fire(specific distance). Here is the code I did so far.. Any suggestion, where is the problem? Or what to do?
using UnityEngine;
using System.Collections;
public class pickup : MonoBehaviour {
public Transform OnHand;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("E")) {
GetComponent<Rigidbody>().useGravity=false;
this.transform.position = OnHand.position;
this.transform.parent = GameObject.Find ("FPSController").transform;
this.transform.parent = GameObject.Find ("FirstPersonCharacter").transform;
}
if (Input.GetMouseButtonDown (0)) {
this.transform.parent = null;
GetComponent<Rigidbody>().useGravity=false;
// Rigidbody.AddForce (new Vector2(1,4), ForceMode.Impulse);
}
}
}
Looks like you have everything pretty much correct. You referred to the Rigidbody correctly to turn off the gravity, but then tried referring to the rigidbody incorrectly to add force.
Do GetComponent().AddForce (new Vector2(1,4), ForceMode.Impulse);
I don't see why that wouldn't work. Take out the '//' of course.
Also, for optimization purposes, you can store the rigidbody in awake or start, than use the variable instead of using GetComponent several times.
something like rb = GetComponent();
then you can just use rb.AddForce().
Hope it helps! If it does, if you can mark it as the correct answer and upvote, do others know it has been answered :).
Related
so I have rigid body and when it collides with another body with low speeds it is working just fine but when it collides with hight speed it goes through the object I've Been have this problem for day and I can't fix it
here's my code
this is my player movement file
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharcterController : MonoBehaviour
{
// Start is called before the first frame update
public Vector3 PlayerMovementVar;
public Rigidbody Rigidbody_comp;
// Start is called before the first frame update
void Start()
{
Rigidbody_comp = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
PlayerMovement();
}
void PlayerMovement()
{
float horizontalAxis = Input.GetAxis("Horizontal")/30;
float verticalAxis = Input.GetAxis("Vertical")/30;
PlayerMovementVar = new Vector3(horizontalAxis,0f,verticalAxis);
transform.Translate(PlayerMovementVar,Space.Self);
}
}
I shouldn't be the one answering this since I have very little knowledge of unity but I'm pretty sure it might be because you are using transform.Translate which I think it avoids collisions try using a character controller instead :)
If you want to use properly Unity physics system you must use Forces instead of Translate direcly your gameobject.
Try this:
Rigidbody_comp.AddForce(PlayerMovementVar);
instead of
transform.Translate(PlayerMovementVar,Space.Self);
RigidBody movement and Transform movement are different from each other, each causes a different type of movement. when moving with a rigidbody, in order to use its physics ability, you should move it instead of the usual transform.Translate.
Rigidbody_comp.AddForce(PlayerMovementVar);
I am trying to write a code in Unity2D that displays a different gameobject after each set amount of time. I am a complete beginner and just started today. This is my code
using System.Collections.Generic;
using UnityEngine;
public class DestroyEnemy : MonoBehaviour
{
public GameObject anim;
public GameObject anim2;
// Start is called before the first frame update
void Start()
{
StartCoroutine(Run());
}
// Update is called once per frame
void Update()
{
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "FriendlyBullet")
{
IEnumerator run()
{
Destroy(gameObject);
Instantiate(anim, transform.position, transform.rotation);
yield return new WaitForSeconds(2);
Instantiate(anim2, transform.position, transform.rotation);
}
}
}
}
The error message says "The local function "run" is declared but never used." What is wrong here?
First of all, I'd like to point out, that you're calling your coroutine only at the start. As a result, it won't ever run again while the game is already running.
I'm assuming the game is a kind of shooter and you want to run the coroutine function when the bullet hits the enemy. So first check if that's what you really want and otherwise I'd move the StartCoroutine to OnCollisionEnter2D.
Secondly, as UnholySheep pointed out, you've missed a capital letter. You're calling run but you have only declared Run. Yes, that's a difference, C# is case sensitive. Functions in C# are supposed to start with a capital letter :).
That's why the IDE or whatever editor is telling you that you declared a function, but you never used it. Local function means that it's declared inside of another function and won't be accessible anywhere else.
It's hard to fix a piece of code from the top of the head as I'm not all that experienced in Unity, only a couple of months so far, but I've fixed those said issues and it should help :).
using System.Collections;
using UnityEngine;
public class DestroyEnemy : MonoBehaviour
{
public GameObject anim;
public GameObject anim2;
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("FriendlyBullet"))
{
StartCoroutine(Run());
}
}
IEnumerator Run()
{
Destroy(gameObject);
Instantiate(anim, transform.position, transform.rotation);
yield return new WaitForSeconds(2);
Instantiate(anim2, transform.position, transform.rotation);
}
}
PS. I've switched your tag logic for CompareTag as it seems to be a better option for doing the same thing :).
Good luck with your game!
Well, I'm trying to make an fps where you shoot tagets and appears an "Arcade-Style" score over them on unity 5, but, I don´t really know how to do it, already tried with an OnCollisionEnter(), but I did something wrong and it didn't worked, What can I do? Below you can see my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Diana : MonoBehaviour {
public GameObject diana;
public AnimationClip Score;
private Animation myAnimation;
/* IEnumerator Wait()
{
myAnimation = GetComponent<Animation>();
myAnimation.Play("DianaScore");
yield return new WaitForSeconds(3);
} */
void OnTriggerEnter(Collider other)
{
Debug.Log("Funcó wacho");
myAnimation = GetComponent<Animation>();
myAnimation.Play("DianaScore");
// StartCoroutine(Wait());
}
void Update () {
}
}
(Sorry for my bad english, I´m argentinian and new in all this coding thing)
I suggest putting this line of code: myAnimation = GetComponent(); into a Awake() function. If the above method does not work, I suggest checking that the Is Trigger is checked for OnTriggerEnter. If the console message (Debug.Log) shows, the problem might be something to do to the animation not the script. Last but not least, check that the bullet actually collides. I know this might sound crazy, but sometimes the bullet might be able to "not get detected" if it has enough velocity. Hope these suggestions work :D .
I am trying to make my player hit an object, destroying the object and triggering an animation, but everything I try causes an error. I am relatively new at c# so the answer may be obvious but I need help. How can I set it up so that the collision will cause the object to disappear and the player to play an animation? Here is the script I am currently trying.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class succ : MonoBehaviour
{
public float speed = .15f;
public static float jumpSpeed = 170f;
void Start()
{
GetComponent<ConstantForce2D>().enabled = false;
GameObject.Find("goal");
}
public bool animation_bool;
private object coll;
private object other;
void Update()
{
OnCollisionStay2D(Collision2D coll);
{
if (coll.gameObject.tag == "succ") ;
{
animation_bool = true;
GetComponent<Animator>().SetBool("succ", animation_bool);
GetComponent<ConstantForce2D>().enabled = true;
Destroy(other.object);
}
}
}
private void Destroy(object gameObject)
{
throw new NotImplementedException();
}
private void OnCollisionStay2D(Collision2D collision2D, object coll)
{
throw new NotImplementedException();
}
}
There are a few things I can see that are wrong, but I'll start by answering your question.
I suggest you change your MonoBehaviour method OnCollisionStay2D to OnCollisionEnter2D. OnCollisionStay2D is "sent each frame where a collider on another object is touching this object's collider". OnCollisionEnter2D is "sent when an incoming collider makes contact with this object's collider".
I believe you are looking for the latter since you only want to trigger this once during the collision. You are also destroying the other object, making it impossible to call OnCollisionStay2D anymore even if you wanted to do so.
You should also remove your Update method. I honestly do not understand what you are trying to achieve there now. All of the OnCollision methods get called automatically; you do not have to call them yourself.
Then you can use the Awake and OnCollisionEnter2D methods as follows
public class Succ : MonoBehaviour
{
private Animator animator;
private void Awake()
{
// You can already get a reference to the Animator on Awake
// This way you do not have to do it on every collision
animator = GetComponent<Animator>();
}
// Use OnCollisionEnter2D instead since the code
// needs to be excecuted only once during the collision
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("succ")
{
// Assuming that you only want to trigger an animation once
// to reflect attacking or colliding, you could use SetTrigger
// instead. Otherwise you need to use SetBool again to set it
// back to false. You should then change the Animator parameter
// accordingly, from a bool to a trigger.
animator.SetTrigger("succ");
Destroy(collision.gameObject);
}
}
}
Apart from this, I have a few things I would like to comment on:
I am not sure what you are trying to achieve by setting your ConstantForce2D component to false on Start and then setting it to true on collision.
You seem to be using GameObject.Find on Start. GameObject.Find is something that should be very rarely used. It can be extremely expensive, especially if your Scene has a lot of GameObjects in it; this is because it simply goes through the Hiearchy, comparing the parameter string to names of GameObjects until it either finds a match or runs out of GameObjects.
Moreover, you are using GameObject.Find on Start to look for a GameObject, but then you do not store that anywhere, making the whole finding process completely pointless.
Overall, I recommend you to take a look at all of the different learning resources offered by Unity themselves. Your question is about fairly basic functionality that is certainly covered during all of the different tutorials.
I am having problems getting OnCollisionEnter2d. I am just starting out with Unity and thought I could throw together a simple version of pong just to get started with the basics. In a script I have attached to a ball I have an OnCollisionEnter2d method but it is not being called.
After looking at other posts where people had this problem I have unchecked "Is Kinematic" and set gravity to 0. After unchecking "Is Kinematic" I had to check the x, y and z constraints on the back wall to stop it getting knocked away by the ball. The ball has a "circle collider 2d" component and the wall has a "Box Collider 2d" one. They both have non Kinematic RigidBody2d components. Another answer to a similar question said to check if collisions between different layers was enabled. They are both on the same layer.
I'm sure I have just missed something simple but I am really stumped. This was meant to just be something quick that I threw together before desigining something a little bit meatier. :) If someone could help me out I would really appreciate it. Code and components below:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class BallController : MonoBehaviour {
public float speed;
public Text scoreText;
private int score;
// Use this for initialization
void Start () {
Rigidbody2D rb2d = GetComponent<Rigidbody2D>();
Vector2 movement = new Vector2(1, 1);
rb2d.AddForce(movement * speed);
score = 0;
scoreText.text = "Score: " + score.ToString();
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2d (Collider2D other)
{
scoreText.text = "test"; // added this line just to see if the method was being called at all
if (other.gameObject.tag == "BackWall")
{
score = score + 1;
scoreText.text = "Score: " + score.ToString();
}
}
}
Ball and back wall components
Sorry I can't paste images inline yet as I don't have the rep.
The correct syntax is OnCollisionEnter2D(Collision2D collision)
You put OnCollisionEnter2d(Collider2D other)
Unity will not recognize a function if it is misspelled even slightly.
(You would not believe how many times I myself fell prey to this.)
Relevant Link: http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html