Normally, I've seen using new Vector2() while calling a constructor and instantiating an object for a class. Like:
Vector2 v2_values = new Vector2(float x , float y);
Here we called to the Vector2 constructor to instantiate an object of Vector2 class and stored it in v2_values variable. That I understood. But I don't understand the new Vector2(2,5) part of the code. Like how can we call an constructor in between and that too without making an object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoverScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Rigidbody2D rd2d = GetComponent<Rigidbody2D>();
rd2d.AddForce(new Vector2(2,5) ,
ForceMode2D.Impulse);
}
}
Related
I'm making a VR test and I've run into a problem and am not sure what to do. Unity keeps saying "type or namespace definition, or end of file expected unity" I am using someone else's code but I am following the tutorial. Here is my code
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VrRig : MonoBehaviour { }
public Transform headConstraint;
public Vector3 headBodyOffset;
{
// Start is called before the first frame update
void Start()
{
headBodyOffset = transform.position - headConstraint.position;
}
// Update is called once per frame
void Update()
{
transform.position = headConstraint.position + headBodyOffset;
transform.forward = Vector3.ProjectOnPlane(headConstraint.up,Vector3.up).normalized;
}
}
you are creating an empty class by having the curly brackets open and closed right after the class declaration. after you declare a code block with class members but never assign it to anything. If you put an opening curly bracket right after the class declaration and close it after all your members, it should work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VrRig : MonoBehaviour
{
public Transform headConstraint;
public Vector3 headBodyOffset;
// Start is called before the first frame update
void Start()
{
headBodyOffset = transform.position - headConstraint.position;
}
// Update is called once per frame
void Update()
{
transform.position = headConstraint.position + headBodyOffset;
transform.forward = Vector3.ProjectOnPlane(headConstraint.up,Vector3.up).normalized;
}
}
I am currently working on making a class accessible from other scripts. Below is what I have coded.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(BoxCollider2D))]
// Start is called before the first frame update
public class _move
{
private float _sizex;
private float _sizey;
public _move(float sizx, float sizy....etc)
{
_sizex = sizx;
_sizey = sizy;
}
public void regularmove(float sizex, float sizey...etc)
{
GameObject _player;
_player = GameObject.GetComponent<GameObject>();
BoxCollider2D bc2d;
bc2d = _player.GetComponent <BoxCollider2D>();
bc2d.offset = new Vector2(locationx + 1, locationy);
}
}
however, when I try to compile it, it gives me an error.
cannot access non-static method"GetComponent"
on this line of code
_player = GameObject.GetComponent<GameObject>();
I do not know why this is happening because I have not declared the class as static, and do not really know the properties of GetComponent that well. Can someone tell me what is happening and how I can solve this?
Also, when I change
GameObject _player;
to
public GameObject player;
the scripts below suddenly cease to work, giving me errors like
cannot resolve symbol _player
what exactly is happening here?
Thanks in advance!
Whatever script creating the instance of the _move class (This is bad naming btw, it should be Move) should also pass its gameObject to the constructor.
// attributes here are not valid if your class is not a MonoBehaviour
public class Move
{
GameObject m_object;
public Move(GameObject obj, ...)
{
m_object = obj;
}
}
if your class is meant to be a MonoBehaviour component, then it has a GameObject member already and you can use the attributes:
[RequireComponent(typeof(BoxCollider2D),typeof(Rigidbody2D))]
// Start is called before the first frame update
public class Move : MonoBehaviour
{
void Start()
{
Debug.Log(gameObject.name);
}
}
I want to trigger an event whenever the player collides with another object, and made the event in the EventManager script, referenced it in the player script, subscribed to it the "onCollision" method but when i try to invoke it in the "OnCollisionEnter2D" method it throws me an error like i would need to subscribe it, and i cant figure out why. How could i invoke it properly? I looked in the tutorials and documentation but i dont understand what i'm doing wrong..
the error: PlayerScript.cs(42,21): error CS0070: The event 'EventManager.onCollisionDo' can only appear on the left hand side of += or -= (except when used from within the type 'EventManager')
EventManager script:
using System.Collections.Generic;
using UnityEngine;
using System;
public class EventManager : MonoBehaviour
{
public event onCollisionDo_dlg onCollisionDo;
public delegate void onCollisionDo_dlg();
}
Player script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class PlayerScript : MonoBehaviour
{
public float speed = 10;
private Rigidbody2D body;
private Vector2 Movement;
[SerializeField]
private GameObject EventManager_reference; // reference to the EventManager via inspector
private EventManager EventMS; // reference to the EventManager script
void Start()
{
body = GetComponent<Rigidbody2D>();
EventMS = EventManager_reference.GetComponent<EventManager>();
EventMS.onCollisionDo += onCollision;
}
void Update()
{
Movement = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
}
private void FixedUpdate()
{
body.MovePosition((Vector2)transform.position + (Movement * speed * Time.deltaTime));
}
private void onCollision() // Method to execute when event triggered
{
print("it collided");
}
private void OnCollisionEnter2D(Collision2D temp)
{
EventMS.onCollisionDo?.Invoke(); // Here is the problem
}
}
Reason behind the issue
The error appeared due to having the event invoked outside the class it was in.
More info: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/event
Potential solution
If you want to be able to invoke your delegate outside the EventManager class, remove the event keyword or add a public method that would allow to invoke the event using an another way.
Extra note
In this case you can use a built in delegate called Action instead of making a custom one.
This question already has answers here:
How to access a variable from another script in another gameobject through GetComponent?
(3 answers)
Closed 2 years ago.
so, my code;
Script one;
using System.Collections.Generic;
using UnityEngine;
public class mousePosTracker : MonoBehaviour
{
public Vector2 mousePos;
public void Update()
{
mousePos = Input.mousePosition;
Debug.Log(mousePos);
}
}
and script two;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class player : MonoBehaviour
{
void Update()
{
transform.Translate(// mouse position);
}
}
the code currently is pretty bare-bones, but I will fix that. so what I want to do is; I want to access the vector2 mousePos variable in script2, so that I can move the player based on the mouse position.
Make a reference on your Player script to your MousePosTrackerScript and use it.
One recommendation, use CamelCase on your class names.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public MouseousePosTracker posTracker = null; //attach it from your Editor or via script
void Update()
{
transform.Translate(posTracker.mousePos);
}
}
One easy way is to use the Find method.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private MousePosTracker mousePosTracker;
void Start(){
mousePosTracker = GameObject.Find("gameobject name which has the MousePosTrackerScript").GetComponent<MousePosTracker>()
}
void Update()
{
transform.Translate(mousePosTracker.mousePos);
}
}
If the gameobject has a tag you can use the FindWithTag method too.
Do like this in your 2nd script, always make sure your script has first letter in caps.
EDIT: if you do not want to give reference (drag&drop) in editor, use the below example. If you want it to be simpler without providing reference in the script, use Lotan's solution.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private MousePosTracker mouse;
void Start()
{
mouse = (MousePosTracker) GameObject.FindObjectOfType(typeof(MousePosTracker));
}
void Update()
{
transform.Translate(mouse.mousePos);
}
}
I´m trying to instantiate a clone of a prefab. I pass as parameter the prefab to clone, the position to put it and the rotation.
The problem is that Unity don't put the clone as the desired position. Any ideas?
using UnityEngine;
using System.Collections;
public class EnemyGenerator : MonoBehaviour
{
public GameObject enemy;
void Start()
{
Instantiate(enemy, new Vector3(30, 30, 30), Quaternion.identity);
}
}