The Script needs to Derive From MonoBehavior - visual-studio

i'm trying to add a script to the Player sprite but Unity gives me this error, can you help me?
using System.Collections;
using UnityEngine;
[RequireComponent (typeof (RigidBody2D))]
public class PlayerMovement : MonoBehaviour
{
RigidBody2D body;
//Upgradable Variables
float moveSpeed = 3f;
// Start is called before the first frame update
void Start () {
body = GetComponent<RigidBody2D>();
}
// Update is called once per frame
void Update () {
Movement();
}
void Movement()
{
float h = Input.GetAxis("Horizontal");
Vector2 velocity = new Vector2(Vector2.right.x * moveSpeed * h, body.velocity.y);
body.velocity = velocity;
}
}

Do you perhaps mean Rigidbody2D? The 'b' should not be capitalised.

You are trying to add "CallbackExecutor" script, not PlayerMovement one.

Make sure the class inherits MonoBehavior. And its type (PlayerMovement) matches its file name (PlayerMovement.cs).

Related

Jumping with CharacterController doesnt work?

I am very new to coding and i am trying to make a FPS, but i can't get the jumping mechanic to work. I am following a tutorial of Brackeys : https://www.youtube.com/watch?v=_QajrabyTJc
I have tried changing the standard jumping bind, i have tried using GetKeyDown(KeyCode.Space) instead of using GetButtonDown("Jump") , but nothing seems to work. Anybody knows how to fix this? I love you. Have been struggling for 16 hours now...
using System.Collections.Generic;
using UnityEngine;
public class playermm : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetKeyDown(KeyCode.Space) && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Here is what I recommend.
Type in this command at the end:
Debug.Log(isGrounded);
It should print true if the character is on the ground. If it prints true, then the error is with your velocity and moving the character or square root expression.
If it prints false, then the problem is with your ground check. you should check the position of 'groundCheck', if it is at the bottom of the charcter, then that is okay. Next, check the 'groundDistance', if the value is about 0.5, it should be okay. Then check the groundMask. If the groundMask is the same mask that the ground is applied to, then that is fine. If it returned true, then one of these is wrong.
Links for extra help:
https://docs.unity3d.com/ScriptReference/LayerMask.html
https://docs.unity3d.com/ScriptReference/Physics.CheckSphere.html
Write back to me.

How to move a cube 3 second in one direction, and next 3 seconds in oppposite direction, alternatively

I am new to unity, and trying something like below, but I can either move only in one direction, or not moving at all.
My cube is a trigger, and is not using gravity. I have checked the Kitematic box. I am trying to make the cube move to and fro, so that player have difficuly collecting it.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
public class movedanger : MonoBehaviour
{
private int mytime = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
MyMover(mytime);
}
void MyMover(int mytime)
{
if (mytime <= 3)
{
transform.Translate(Vector3.forward * Time.deltaTime);
mytime++;
}
else
{
transform.Translate(-Vector3.forward * Time.deltaTime);
mytime = 1;
}
}
}
What you are looking for is to and fro movement of an object. You can achieve this with Mathf.PingPong() function instead of using translate. I have tested it with a cube, you can set the minimum and maximum distance it should move to and the speed at which it travels. Since you want the cube to move 3 seconds in one direction at a time. You can calculate the speed as distance/time so the max distance it should travel to from the current distance and the time (3 seconds) it takes. Hope this helps.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCube : MonoBehaviour {
public float min = 2f;
public float max = 8f;
public float SpeedOfMovement = 2f;
// Start is called before the first frame update
void Start () {
}
// Update is called once per frame
void Update () {
transform.position = new Vector3 (Mathf.PingPong (Time.time * SpeedOfMovement, max - min) + min, transform.position.y, transform.position.z);
}
}
With InvokeRepeating you will call the same MoveCube method every 3 seconds.
using UnityEngine;
public class MoveDanger: MonoBehaviour
{
public bool isForward = false;
private void Start()
{
InvokeRepeating("MoveCube", 0f, 3f);
}
private void MoveCube()
{
if (isForward)
{
transform.Translate(Vector3.back);
isForward = false;
}
else
{
transform.Translate(Vector3.forward);
isForward = true;
}
}
}
Honestly the best and easiest way to do something like this, once you get used to it, is just to
Use Unity's incredibly simple animator system:
(Essentially just click "new animation" and then drag the object around as you want it animated.)
There are 100s of tutorials online explaining how to use it.
It's one of those things where once you use it and see how easy it is, you will do a "facepalm" and never bother again with other ways.
It's really "the Unity way" to achieve the goal here, dead easy and flexible.

Getting errors when i try to get game to restart when i hit an obstacle or fall of ground

Please excuse me I'm a complete novice at all this but I'm trying to make a game following "Brackeys How To Make A Video Game" I'm on video 8 if that helps. I can't seem to find what i have done wrong i have added my scripts for "player movement", "player collision" and "game manager". Please if there is anything else you need to help me please ask i really don't want to give up just yet was really enjoying doing this.
Thank you all
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
// This is a reference to the Rigidbody component called "rb"
public Rigidbody rb;
public float forwardForce = 2000f; // Variable that determines the forward force
public float sidewaysForce = 500f; // Variable that determines the sideways force
// We marked this as "Fixed"Update because we
// are using it to mess with physics.
void FixedUpdate ()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d")) // If the player is pressing the "d" key
{
// Add a force to the right
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a")) // If the player is pressing the "a" key
{
// Add a force to the left
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
using UnityEngine;
public class PlayerCollision : MonoBehaviour {
public PlayerMovement movement; // A reference to our PlayerMovement script
// This function runs when we hit another object.
// We get information about the collision and call it "collisionInfo".
void OnCollisionEnter (Collision collisionInfo)
{
// We check if the object we collided with has a tag called "Obstacle".
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false; // Disable the players movement.
FindObjectOfType<GameManager>().EndGame();
}
}
}
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
bool gameHasEnded = false;
public float restartDelay = 1f;
public GameObject completeLevelUI;
public void CompleteLevel ()
{
completeLevelUI.SetActive(true);
}
public void EndGame ()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME OVER");
Invoke("Restart", restartDelay);
}
}
void Restart ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
when i fall off ground:
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.FixedUpdate () (at Assets/Scripts/PlayerMovement.cs:32)
when i hit an obstacle:
NullReferenceException: Object reference not set to an instance of an object
PlayerCollision.OnCollisionEnter (UnityEngine.Collision collisionInfo) (at Assets/Scripts/PlayerCollision.cs:15)
It seems to me that FindObjectOfType<GameManager>() is returning null, which is causing a null reference exception when you attempt to call the EndGame function. This most likely means that there is no object in your scene with the GameManager component on it. The solution to this problem is simple:
Create an empty object in your scene and add the GameManager component to it. This will fix the error in this instance, but it could happen in the future if you're not careful. It is also a good idea to check if you found an object or not before calling functions on it:
GameManager gm = FindObjectOfType<GameManager>();
if (gm != null)
{
gm.EndGame();
}

Not able to Shoot in the direction of the hand

I have designed a model in blender and imported in Unity and applied ThirdPersonController, ThirdPersonCharacter, ThirdPersonUserControl on it and got animation y following the guidelines, now i have created a script for shooting the bullets and attached it to the rigged hand/gun. But whenever i click "Fire1" the bullet is getting shooted in other direction..
I want when i move the mouse, the hand should move in the direction of the mouse + body should rotate in the direction of the mouse (if on backside) and when i left click, it should fire a bullet in the direction of the mouse(one at a time).
Video for better understanding - http://tinypic.com/r/34yohli/9
I tried a script, but its not following the way i want.
Shoot.js
#pragma strict var projectile : GameObject;
var fireRate = 0.5;
private var nextFire = 0.0;
var shotDelay = .5;
function Update ()
{
if (Input.GetButton ("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
var clone = Instantiate (projectile, transform.position, transform.rotation);
}
}
MouseMovement.cs
using UnityEngine;
using System.Collections;
public class MouseMovement : MonoBehaviour
{
public float speed = 1.5f;
private Vector3 target;
void Start()
{
target = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.x = transform.position.x;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
To detect the movement of the mouse you should use the Input.GetAxis("Mouse X") or Input.GetAxis("Mouse Y"). If you want the camera to move with the character you can set it as a child of the character. You can check the MouseLook Script for more info.

Unity 2D controller coding issues

I am kind of new to Unity and I am trying to make a game using various tutorials for character controlling but recently I ran into a tutorial where they used this code:
using UnityEngine;
using System.Collections;
public class controller : MonoBehaviour {
public float maxspeed = 10f;
bool facingRight = true;
void Start ()
{}
void FixedUpdate ()
{
float move = Input.GetAxis ("Horizontal");
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
if (move > 0 &&!facingRight)
Flip ();
else if (move <0 && facingRight)
Flip ();
}
void Flip()
{
facingRight = !facingRight;
Vector3 theScale = tranform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Thing is that it does not work when I type it into my MonoDevelop Unity Javascript. So I would like to know what I am doing wrong.
Thank you in advance!
The codes are meant to be in c# I think. Try typing them in C#.

Resources