#š»ācode-beginner
1 messages Ā· Page 46 of 1
I don't, I just remeber a time when they were off to the right and not spacing out the text
are you certain you aren't thinking of something else? because code lens has looked like that for years
or maybe you're just remembering a time when you didn't have it due to vs code not being properly configured
It just spaces out the text a lot vertically and drives me a bit crazy
I mean I don't see it's superior over hitting [shift+F12]
Can you declare two prefabs?
Sure
I just shift+F12 something if I need to know where something is being used. I prefer to have the code lens off
Although, that's partially because VSCode gives the lens an entire line, iirc
rather than a cute half line
Same, I just find it annoying. How many times something is referenced isn't really the kind of information that needs to be visible all the time.
i mostly just care about whether it's used at all
isnt that the same as doing ctrl+f when having the function marked?
That would search the current file for things with the same name.
well you can apply filters to it to make sure
References are based on code analysis.
š
So it doesn't matter if I have the word "Hit" all over the place in my code
thats built in to vs right? not a unity thing
This will only show me things that refer to this specific identifier
It's in your IDE, yes
so VSCode/Visual Studio/Rider/etc.
great, might show this in my class
Text search usually works fine within a single file, but short/common names will cause lots of problems
I guess you'd say that this is based on semantics -- the actual meaning of your code
thanks took me quite a while, its work fine now
i want a prefab to start in front of the player and then disappear when thrown. how would i achieve this
the game is about throwing darts
(3D)
get the player position then add a few units in front (forward) of it . . .
would that be in an void update?
you place it in your code where you need the dart to appear . . .
can i just show u my code lol
Why dose the foot moves only up and down if i add the eight offset
is there any other code that also affect the position of the leg?
nope, thats the only script in the hole project
private void Update()
{
Ray ray = new Ray(transform.position + (Vector3.up * .5f), Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
footPlacement = hit.point + (Vector3.up * heightOffset);
}
transform.position = footPlacement;
}``` i even tyed to do this way'
can you print out what is being hit
the ray hits the ground only
is that the only output you get if you move it around?
yes
ok now do the same but with the offset
without the offset the leg moves how is supposed to but the height isn't, and there is no collider hit appearantly
i removed the height offset also from the ray
so there is different things being hit depending if you use offset or not?
Ray ray = new Ray(transform.position, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
{
footPlacement = hit.point;
Debug.Log(hit.collider.name);
}
transform.position = footPlacement;```
with this code the ground is hit, and the position of the foot gose to where is supposed to, but there is no debug
but with this code it debugs that it hit the ground
the ground is always hit, there are no other colliders in front of the ray and foot is contolled by one script
have you fact checked that nothing else is being hit?
not just as you assume?
yes, in fact only the ground has a collider on hit, and i lifted the spider up to check
only the ground is hit
my exact problem is that the foot dosen't maintain the position when moved forward or left and right and backwards when adding an offset to it
it moves up and down tho
can anyone help me with Building my game? i get errors
This is wierd
i never had build issues
that only makes sense (to me at least) if there are different things being collided with, without you noticing it
chat gpt can probably help
Would be a good idea to post your errors here so we can help š
I've been struggling so long with it. I've made a 3d game on unity but the player (sphere) moves (wasd) the opposite direction of what it's supposed to be (w goes back, a goes right), I've tried everything
I suspect that maybe I've created the game in the opposite direction of the camera, but I still rotated the camera by 180, and it didnt work, the player too.
here's the code
// Include the namespace required to use Unity UI and Input System
using UnityEngine.InputSystem;
using TMPro;
public class PlayerController : MonoBehaviour {
// Create public variables for player speed, and for the Text UI game objects
public float speed;
public TextMeshProUGUI countText;
public GameObject winTextObject;
private float movementX;
private float movementY;
private Rigidbody rb;
private int count;
private bool isGrounded;
// At the start of the game..
void Start ()
{
Debug.Log("Player position: " + transform.position);
// Assign the Rigidbody component to our private rb variable
rb = GetComponent<Rigidbody>();
// Set the count to zero
count = 0;
SetCountText ();
// Set the text property of the Win Text UI to an empty string, making the 'You Win' (game over message) blank
winTextObject.SetActive(false);
}
void FixedUpdate ()
{
// Create a Vector3 variable, and assign X and Z to feature the horizontal and vertical float variables above
Vector3 movement = new Vector3 (movementX, 0.0f, movementY);
rb.AddForce (movement * speed);
}
void OnTriggerEnter(Collider other)
{
// ..and if the GameObject you intersect has the tag 'Pick Up' assigned to it..
if (other.gameObject.CompareTag ("PickUp"))
{
other.gameObject.SetActive (false);
// Add one to the score variable 'count'
count = count + 1;
// Run the 'SetCountText()' function (see below)
SetCountText ();
}
}
void OnMove(InputValue value)
{
Vector2 v = value.Get<Vector2>();
movementX = v.x;
movementY = v.y;
}
void SetCountText()
{
countText.text = "Count: " + count.ToString();
if (count >= 12)
{
// Set the text value of your 'winText'
winTextObject.SetActive(true);
}
}
}```
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
alright wait a min
movementX = -v.x;
movementY = -v.y;
can you expand the last one?
Does any of the errors have any explanation text?
oh my god
oh my god
it's been 2 days and you saved me
you're a god, thanks!!!!
some have a lot of wierd texts
OK ALL of them have wierd texts
Expand the burst ones and read them
there is no other thing hit by the ray
it tells you right there why it doesn't work
i added VS2019
only thing i can recommend you doing is
debug all of the information
get as much info from the code as you possibly can
from there, scan for anything strange
What else do i need?
How can I change that code of mine, in a way that if the player touches an object, it loses points? (It can only earn points for now)
Please follow what vertx said above, that might tell you what you need to do
Look at OnCollisionEnter
in visual studio -> Tools -> Get Tools & Features -> Universal Windows Platform development
*Is my guess
there is nothing really to debug, the offset is alright, the ray hits the ground
do a ray debug visualiser (displays a 2d ray going from origin to target location)
Do you mean online or a channel here? sorry i'm new
nope
doesnt work
its an event basically
void OnCollisionEnter(Collision colliderObject)
might not be exactly what he means
thank you, I know of it from our lesson i'm just not sure how to work with it, i'll experiment a bit
ok what do i do?
Expand the burst ones and read them
Expand the Burst-related errors and read them.
i need to submit this project tommorow to school
it dose hit the ground 100%
then idk dude
i will burn unity to the ground
thanks!
do it
It's telling you which components you need to install
how do i install?
using the visual studio installer
Click on modify on 2022
i used 2019 to make all scripts
Then tick "Universal Windows Platform development" & "C++ Universial Windows platform support for vNNN build toold (ARM64)" + all the others that your error discribes
It just needs to be installed
to have the sdk available
doesnt matter which one you use in the end
Hmm oh wait, your compiler tries to use 2019 if i see that right, well then you might have to modify 2019
i did that
In the error you posted are 4 packages you need to install
at the top should be a tab where you can look for individual components
use the search bar in there
should I write the script in the player's script, or create a new script?
// - instantiates an explosion Prefab when hitting a surface
// - then destroys itself
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
public Transform explosionPrefab;
void OnCollisionEnter(Collision collision)
{
ContactPoint contact = collision.contacts[0];
Quaternion rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
Vector3 position = contact.point;
Instantiate(explosionPrefab, position, rotation);
Destroy(gameObject);
}
}``` this for example, do I replace "gameobject" with the name of the object I want it (the player) to be collided with? I'm not good with coding..
If you already have a script on your player you can just plug the OnCollisionEnter function into it, keep in mind, in order to trigger collision events, your player needs to have a Rigidbody component
the term gameObject in any MonoBehaviour returns the gameobject your script is on
The cs should be after the triple back quotes by the way. That way you get colors.
I copy pasted it as it is from the website
so how do I make it so the player recognizes the "enemy"? do I use a tag or something like this? or write the enemy's name in the code somewhere?
What is explosionPrefab
I don't know exactly how the script works, I took it from the website https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
I want the player to have a point removed when it collides with an enemy/grenade
but I don't know what to write
is this a runtime error? it doesn't look like it is
This says you wrote the name in PlayerController. But the code above is ExampleClass..
Did you declare it in PlayerController, or only ExampleClass
Where do you define a variable explosionPrefab
ok so I wrote this cs void OnCollisionEnter(Collision collision) { ContactPoint contact = collision.contacts[0]; Quaternion rotation = Quaternion.FromToRotation(Vector3.up, contact.normal); Vector3 position = contact.point; Instantiate(explosionPrefab, position, rotation); Destroy(gameObject); } in playercontroller
sorry for any confusion
did you also add the public Transform explosionPrefab;?
no
that's your problem then
Instantiate(explosionPrefab, position, rotation); <- on this line it doesn't know what explosionPrefab is because you've not defined it
youre right it worked fine now
do i add box collider on the enemy?
because the player goes through it now
whatever has this script will need a collider yeah
otherwise OnCollisionEnter will never happen
if you have a floor or something with a collider then that will be triggering that method too
Hello
My AI doesnt go to the target. I use SetDestination that returns a bool -> True if set successfully and false if isnt. I get a returned value "true", but my AI doesnt go to the Set Destination. I'd like some help here
you'll need to interrogate the collision and find out where it came from, the easiest way probably is to add a tag to your projectile (or whatever it is) and check for that, if it has the right tag then do the explosion/destroy logic
otherwise just ignore the collision since it'll be a floor/wall/etc
Can't help without code
not enough info here to go on, will need code examples etc
IEnumerator SummonGhostRoutine(){
//Make art material Emission
//art_material.SetColor("_EMISSION", Color.red);
//Play sound for art
art_audio.Play();
//Make art particles play ONCE
particle.Play();
//Play Ghost Animation (DONE)
animator.Play("GhostAnimation");
yield return new WaitForSeconds(8);
//Set a barrier so player WONT get in spawn
barrier1.SetActive(true);
barrier2.SetActive(true);
//Ghost speed = 0
agent.speed = 0;
//Ghost set target
if(agent.SetDestination(player.position)){
Debug.Log("true!");
} else {
Debug.Log("Fault");
}
Debug.Log("!");
yield return new WaitForSeconds(5);
//Ghost speed = NORMAL SPEED
agent.speed = 5;
Debug.Log("!1");
//Start timer
TimerStarted = true;
}
sent it
what do I tag it as?
whatever makes sense!
and also, what do I do after I tag it? I don't assume "tagging" will magically work on its own
no, if you add a tag to your projectile prefab (or however you're doing it), you can do collision.gameObject.tag to fetch the tag of the gameobject that the collider is attached to
then check if that == "Projectile" or whatever you name the tag
for (int i = 0; i < 2; i++)
{
Vector3 tmpPosition = transform.position;
switch (i)
{
case 0:
tmpPosition.y = tmpPosition.y + offset;
break;
case 1:
tmpPosition.y = tmpPosition.y - offset;
break;
}
RaycastHit2D[] hit = Physics2D.RaycastAll(tmpPosition, rb.velocity.normalized, distanceFront, mask);
Debug.DrawRay(tmpPosition, rb.velocity.normalized * distanceFront, Color.red, 0.2f, false);
(slightly more code below)
is there a better way to code this instead of a switch?
where do i add this? collision.gameObject.tag
sorry im really bad
oh sorry, inside the OnCollisionEnter method, the Collision collision parameter that gets passed in is details about the collision, collision.gameObject is the other gameobject that's involved in the collision (not the gameobject that the OnCollisionEnter method is on
gameobject.tag = tag from the gameobject this script is on
collision.gameobject.tag is the tag from the object that was collided with
could anybody pls-
where do i place it?... š„¹
collision.gameObject.tag
collision.gameObject.tag inside that method will be the tag that you're colliding with, that's the hint! what did you name your projectile tag?
Are there any errors? Have you baked a nav mesh? Is your target within the nav mesh bounds? Does your AI have a path they could take to get there meaning that the path isn't blocked or the AI isn't isolated from the target?
I tagged it as "Enemy"
Are there any errors? No
Have you baked a nav mesh? Yes
Is your target within the nav mesh bounds? Yes
Does your AI have a path they could take to get there meaning that the path isn't blocked or the AI isn't isolated from the target? Yes
Ima try smth rn
okay, so in OnCollisionEnter, collision.gameObject.tag will either be "Enemy" (if an enemy has touched the player), or "" if something else has
so you can check for if the tag is enemy, and then do whatever you like, or more likely if its not enemy, do nothing
okay so probably worth understanding what exactly that example code is doing, going line by line:
- fetch the contact point of the collision
- fetch the rotation opposite to the contact point (i think, i'm rubbish at rotations)
- fetch the position in space of the collision contact
- create an instance of an explosion prefab at the position and rotation from above
- destroy this gameobject
the question is, when do you want this set of instructions to happen? on every collision, or only on collisions with the enemy?
Show the logs you're getting and the order you're getting them in
Turn off collapse if it is on
to sum up those 5 lines i described, it makes an explosion at the collision point and deletes this gameobject
I just want, whenever the player touches the enemy, the player's points get reduced by 1 each time
but I don't tknow how to do that š I don't understand the collision examples i find online
yep! will get to that but it's important to understand the code that you have just now rather than getting ahead
if you understand what you have it's easier to understand what needs to change
I agree
so at the moment, when the player touches any collider, it will create the explosion prefab and delete itself right?
be that a floor, wall, etc
well, that's not what I want
but currently, when I start the game, the enemy instantly dies
somehow
i know but i'm saying that's what's happening right now with the code you have
So log the object you collided with to see what is hitting it
so the next step towards your goal of "take a point away when the enemy touches the player", is to adapt your code so that the explosion/delete effect only happens when an enemy touches you
then after that, we can change the explosion/delete to be "remove a point"
so, going back to what i was saying before, inside your OnCollisionEnter method, the collision variable lets you see the tag of whatever gameobject touched you, accessible through collision.gameObject.tag - you want it so that your code in OnCollisionEnter only runs if the other tag is "Enemy"
var otherTag = collision.gameObject.tag; could be the first line in your method, to poke in the right direction
code works but the enemy dies instantly without doing anything
there's more to write, but it's worth trying to figure it out, essential programming skill!
how do I log it?
Debug.Log("some string") is the method for logging
Debug Log should literally have been the first line of code you ever wrote in unity
is your IDE even configured
ide?
VS
visual studio?
okay so you can do a Debug.Log(collision.gameObject.tag) in your OnCollisionEnter method to print the tag of the other gameobject (spoiler, it will probably be an empty string if it's the floor and it doesn't have a tag)
hmm this would not underline in the code editor as its a runtime error
you have to check inside the VS when you write something incorrect does it underline it red ?
right this should show in VS
i did this on purpose
they're wondering if you look at that line in VS, is there a red underline on it?
at the end of the line
Then you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
So it shows errors as you make them
is it needed to do that config even if all is running good? or is it just if your ide is not working proper with it, a bit confused now
If errors are underlined in red in your IDE, it is configured
If not, then do it
what do i even download from the site? it's all so confusing...
i see ill go check now quick quick
I use 2022 vs
Click on the link for the IDE you're using and follow the instructions
@polar acorn Late but, here
IEnumerator SummonGhostRoutine(){
//Make art material Emission
//art_material.SetColor("_EMISSION", Color.red);
//Play sound for art
art_audio.Play();
//Make art particles play ONCE
particle.Play();
//Play Ghost Animation (DONE)
animator.Play("GhostAnimation");
yield return new WaitForSeconds(8);
animator.StopPlayback();
//Set a barrier so player WONT get in spawn
barrier1.SetActive(true);
barrier2.SetActive(true);
//Ghost speed = 0
agent.speed = 0;
//Ghost set target
if(agent.SetDestination(player.position)){
Debug.Log("Target Set");
} else {
Debug.Log("Target set Fail");
}
Debug.Log("!");
yield return new WaitForSeconds(5);
//Ghost speed = NORMAL SPEED
agent.speed = 5;
Debug.Log("!1");
//Start timer
TimerStarted = true;
}
I have an animation playing before setting a target
And this is with collapse disabled right? I want to be sure that you're not starting multiple coroutines before the first one finishes
Oh forgot
forgot to say, thanks for the info
i did it
poor lad got 3 mentions in a row
you didnt finish the setup / missed a step
regen project files in External Tools after
why is everything going wrong with me
I click "OK" but the window opens again, without stopping
we have no way of determining what you did and didnt do by this screenshot alone..
ill try to follow the website again, brb
Okay, but each of those logs you put in that code are each only run one time right?
You don't have multiple coroutines stacking?
Then I would first try to fix that Animation Event error you're getting. An error could be preventing your code from executing. It's unlikely but might as well eliminate it as a possibility
Either remove that animator event or assign it a function
ok I added the "game dev with unity" option, but I don't know how to setup the ide
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
Can you show the full !code for the function with this coroutine on it?
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Sometimes all you gotta do is ask the question and the answer reveals itself
there is "wintext" how can i write more than 1 "wintext"? is there like, an endtext/losetext?
I want to have a text show up when the player loses
{
countText.text = "Count: " + count.ToString();
if (count >= 12)
{
// Set the text value of your 'winText'
winTextObject.SetActive(true);
}
if (count < 0)
{
winTextObject.SetActive(false);
}
``` something like this
There's whatever you want
you can write the code to do anything
you could also just use a single text object and change what it says
guys, how to make a camera movement like swipe left/right with bounds?
wintext is just a variable you made
If you want more text objects, make more
That's not a built in Unity thing
Show where you created it
it should be TMP_Text, not GameObject
well actually I guess if you're just calling SetActive GameObject is fine
but WinText is a TMP_Text
I just tested it, it works
probably best to keep them consistent
anyone familiar with InputManager? I was able to make it so when I press WASD my character moves and changes to the running animation, but I also need a transition into the idle animation when I stop moving.
I already have a condition set, I just don't know how can I code "if I press nothing, do this".
if(inputs != Vector2.zero)
nah fr you gotta show the code
InputSystem is worth learning. Even if learning it absolutely sucks
Check if an axis is zero (or if the absolute value of an axis is less than some "deadzone" value you decide on)
ohh isn't inputmanager the old one?
idk. I thought itās just called Input
it is
in Unity it's called InputManager
InputManager is the old system, accessed via the Input static class
how to make it so the game restarts after 2 seconds, and NOT instantly?
love the names Unity uses
a timer
or async
Task.Delay barely works in unity
Coroutines are good for waiting for specific parts of a frame of Unityās calculations.
Async works outside unity, and lets you return values
Thatās the tldr
But it's also a bit of an "infection". More and more of your code will need to become async to interact with it and it's a lot harder to just plop into a project for a single use
yeah async is a double edge sword
hi guys!
It's like a zombie virus
with unity inapp 4.9.3 we are safe?
im using Version 4.9.3 - June 14, 2023 of inapp purchasing from unity
whats that? is this coding related?
the code of system purchases is not?
this isn't a specific coding question
If it's a code problem, show code
in general, once you start with coroutine/async, it is hard to switch
and a lot of unity devs had issues migrating out to other engines because they were used to Coroutines
Im glad unity has entry points to async /IEnumerator
private async void Start() | private IEnumerator Start()
Last assistance please
When the player falls in a hole, the game restarts
but when I tried to make it so when the player's points go below 0, it doesn't restart
this alone isn't helpful
what more should I give? the code?
thats a start
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ReloadScene : MonoBehaviour
{
void OnTriggerEnter(Collider col)
{
if (col.CompareTag("Player"))
{
Invoke("RestartScene", 2.0f);
}
}
void RestartScene()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
``` this is for when the player falls down
it restarts after 2 seconds
I tried to do this for when the player's points go below 0 ```cs void SetCountText()
{
countText.text = "Count: " + count.ToString();
if (count >= 12)
{
winTextObject.SetActive(true);
}
if (count < 0)
loseTextObject.SetActive(true);
Invoke("RestartScene", 2.0f);
}```
Are coroutines only ideal for things tied to the frame rate like animations?
No
Good for lots of things
Can you run them on the FixedUpdate cycle? I was looking over the execution order and saw they fall under Update so I wasn't sure
Afaik, they just run after update
FixedUpdate is a whole different cadence
you can yield return new WaitForFixedUpdate to continue right after the next FixedUpdate
so you were suggested coroutines and you didn't use them.?
also where is SetCountText even called at
Oh hell yeah- is there a list of the various yields?
Edit: Also when you schedule the coroutine, I figure it's like calling the method immediately which then continues until it hits a yield return?
I just used it by searching around
it's working now thanks
is it possible to declare some kind of method in class and in its constructor take in implementation of it as a parameter lol
like if I declared Action type and I could pass in Action but I want to keep implementation inside class
wdym by "keep implementation inside class"
https://hatebin.com/scopwfdtru this imaginary example but instead of making up methods outside class and passing them in have one inside it
idk how to explain 
like legit change how that method behaves ig
i genuinely do not understand what it is you are trying to achieve. the only way to pass methods around is with delegates like Action
yeah what's the problem you're trying to solve?
I need 4 instances of class with method which does in each of them almost exact same thing
but like math stuff I cant make base implementation then override in child and add onto it or something
i'm just gonna drop this here and hope you actually read it https://xyproblem.info
It doesn't make sense to take a value from constructor and also keep that implementation purely in class
why do you need the 4 instances that do slightly different things, probably going to need an example because it really smells like @slender nymph s link
Instead of obfuscating what you're trying to do by showing fake examples, just show what youre doing with the real problem
Because right now it just sounds like you need a delegate and that's all
public void SomeMethod(Action someExtraAction)
{
// Do common things
someExtraAction.Invoke();
}
this will do what you're describing there
as far as keeping the implementation of the extra action in the class, you could define the actions you want inside the class, and have the callers use them like instance.SomeMethod(instance.ExtraAction1)
Help:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
Your script should either check if it is null or you should not destroy the object.
what is your code?
I am trying to instantiate another prefab but it will not because of the error
Yea thats what I wanted I didnt thought I can set actions like this lol ty
you're instantiating a prefab or scene object?
are we meant to guess what the code is from your description? or would you care to share it?
My bet is he referenced a scene object and not the prefab from the project tab
You were right
Thanks
You owe me a coke
I will come when you least expect me
heey, does anyone knows how could i do this image to have the same size in all screens?
not a code question. check the pins in #š²āui-ux to learn how to anchor and scale your UI
ok, sorry, then i post the question there
or you could just look at the pins in that channel and learn how to do it
i couldn't find the solution
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed = 5f;
puplic transform movePoint;
// Start is called before the first frame update
void Start()
{
movePoint.parent = null;
}
// Update is called once per frame
void Update()
{
if(Math.Abs(Input.GetAxisRaw("Horizontal")) == -1f)
(
movePoint.position += new Vector3(Input.GetAxisRaw("Horizontal"), Of, Of);
)
if(Math.Abs(Input.GetAxisRaw("Vertical")) == -1f)
(
movePoint.position += new Vector3(Of, Input.GetAxisRaw("Vertical"), Of);
)
}
}
This is my script and here is the errors
do you see red underlines in your code?
'puplic'
then you didn't follow all of the instructions for configuring your !IDE like you claimed you had earlier
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
you should set up your ide and it would warn you that there's multiple problems with your syntax
puplic, using brackets instead of braces
lowercase t in transform
idk how to do that
im in the docs but im now sure where to go
thats where i am
then follow the instructions
ik they are confusing
what are you confused about
idk where to put the editing revolved thing
the Editing Evolved section just lists the features you will have when vs code has been configured. it's not a "thing" you "put" anywhere
follow all of the instructions above that
i did that
then regenerate project files and restart vs code
oh and i meant debugging my bad
it's like you didn't even bother reading what it said
Try restarting your computer
bet
Sometimes when you get the extensions, the PATH is not updated until restarted
Otherwise you don't have the SDK and need to get it, but try the restart first
or they missed getting the extension entirely
Guys, i wanna center my wheel as the same center of my car, how i can solve this?
Like, reseting the Pivot for the center of the wheel
Start by switching this to Pivot so you can actually see what's going on
u can use empty containers.. and adjust the model as a child to represent where u want the pivot.. and then use the parent's pivot (center)... or you can pull the models into blender or some other 3d software to adjust the pivot urself
Hi, strage behavior with NavMeshAgent.destination: I have a Vector3 "destination", where x = 512.0001, that i assign to a NavMeshAgent.destination, but the destination than reads a Vector3 where x = 512 without the .0001. Afterwards, when checking navMeshAgent.destination == destination, it returns false. I want to check at a later time, whether navMeshAgent.destination equals the destination i (might have) set earlier, but this behavior screws that up. Any ideas on that?
Never check float values for equality
Never use == with float comparisons
Check if the distance is below a threshold
Or use Approximately
https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
== and floats are bad juju, unless you use == 0f to check for having assigned a zero, and not having changed it at all
Ahh yes, i read that before. Thanks for the advice! I'll try using Approximately
i find unity makes float == work somehow, but itās still pretty bad
Q: Is there a light way to sort (usually very small) subsets of lists?
eg, I have a list of size 20, and just need to sort the elements in slots 0-3
How i can center my wheel?
I centered it in blender
u have to Apply the transform
and then re-export it as a fbx, obj or w/e
if u did it correctly it'll show the new pivot when u swap into Pivot mode as someone already posted
changing that to Pivot
When you get multiple hits from a Cast, is it sorted by distance?
one more cast-related question: If i cast and hit something multiple times, do I just get the first result?
example
The reason that Unity writes documentation is so that you can read it
cool. how about this method?
https://docs.unity3d.com/ScriptReference/Collider2D.Cast.html
As the size of the array is decided by you the results are most definitely undefined
If a project is halted by a break point, is there a way to prevent the unity editor from locking up?
I moved some monobehaviour .cs code around through the project window and now suddenly none of the moved code is able to find types and namespaces that it had no issue with before moving it - why is this the case, how do I fix it and prevent it from happening again?
none of it was editor code and I didnt move it out of the project or out of assets yet somehow it cant find the rest of the code and this has never happened to me before
I am creating a game where you splat fruits. I would like to display a splat effect when you splat the fruits, how would I do this? I have the splat prefab
visua; studio can't even find the code that is being referenced when I search the entire proj for it, but its not been removed from the proj I even have the other files OPEN in visual studio
It is likely that one or both of them have changed Assemblies. If your project uses Assembly Definitions, each one contains only its own folder and any child folders, with each file belonging to only one assembly. You can set references in the inspector for one assembly definition to reference the other. In this case, whatever assembly definition this script belongs to needs to reference whichever one UIProto_ReceiveInputs belongs to
Also, if Unity doesn't have any issues with these and it's purely in your IDE, consider regenerating project files so it knows the new locations of those files
I'm trying to make a very basic script that sends you to another scene when the enemy collides with the player but for some reason it's not working. Are there any noticable issues?
How would I determine if we're using assemblies definitions? We're using plastic as a versioning software if thats related?
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt have a 3D Rigidbody on at least one of them
code team confirms Assembly Definitions are in use
You would look for any files with the extension .asmdef in the assets folder
Both have colliders, aren't set as triggers, and both have a rigidbody
That's how they move in other scripts
Is the scene called Jumpscare?
So, each script "belongs" to a single assembly definition. It would belong to the "closest" one in the file system. If it's in the same directory, it'd be long to that. If there is not one in its directory, but in a parent directory, it'd belong to that one
yes
With the exact same capitalization
Wait I think I figured it out
Typically it spits an error when I forget to add it to the build settings
So I figured I already did
I see, and by moving the script ive broken that
Ok now it works
Yep. UIProto_ReceiveInputs belonged to an assembly defintion that this script's assembly definition had a reference to, and now it's been moved to one that does not
(or the other way around, this script moved into a different assembly definition that does not have a reference to the one UIProto_ReceiveInputs belongs to)
usually the point of the breakpoint is to basically freeze the state of the machine. Not locking up the unity editor would allow scripts etc to change that state while youāre looking at it
which is not acceptable.
Unity doesn't do anything special for float. It does, however, give some wiggle room when checking if two vectors are equal with == https://docs.unity3d.com/ScriptReference/Vector3-operator_eq.html
The game and the editor are running on the same thread. So, no
maybe thatās why I thought it would work
I check for float equality when I am using something like MoveTowards
It will reach an exact value.
@buoyant knot @swift crag I mean just to be able to select game objects, to see their stats, where they are, their gizmos etc. Not having the "game" run or change anything
I am unable to see my debug.log messages
that doesn't sound like a code issue. but you have probably hidden them in your console
I am sure the function works so I don't know why the message won't display in the console
you have probably hidden them in your console
If you want to display effects after you slice a fruit, you would instantiate it, right?
hey friends. in one of my gameobjects scripts i'm trying to instantiate a prefab but the script doesnt seem to find said gameobject/class(?) [despite the desired script having the same name verbatim]. i've tried to drag the script/gameobject prefab into the inspector of the script & game object doing the instantiating but it doesnt let me drop it in. the wierd thing is that i've managed to make this work on 3 other objects/scripts but i cant remember how
I do not see a KingsForkProjectile component
are you able to elaborate please? KingsForkProjectile is both a script and asset, verbatim, in my assets folder
or was that other prefab not the object you were trying to drag into the first object?
the name of the prefab is irrelevant
the crescent dart controller prefab was an example where i did manage to get this working
okay so show the object you are trying to drag in
None of the pictures showed the KingsForkProjectile
i've just had a look at the projectile prefab i wanted to spawn in and realised i hadnt actually dragged the corresponding script onto it, i had gotten a bit ahead of myself. thats actually fixed the issue. thanks
I mean, if you're not using it, then it doesn't matter if it exists or not
I need to use it
Maybe you should actually elaborate on the issue instead of posting in vague terms
I want my debug.log statements to show in my console but it will not
So the class is not working
If they are not showing in the console then that code is never running
Show code
I've been working a little bit on refactoring the code for my player. I'm trying to get the health management logic outside the player class and onto a class of it's own.
I feel like I am doing something really wrong here.
Can anyone point if that's how composition should be achieved?
public class HealthManager : MonoBehaviour
{
public void SetHealthToMaxHealth(int currentHealth, int maxHealth) {
currentHealth = maxHealth;
}
public void ReceiveDamage(int damage, int currentHealth, int armour){
if (armour != 0 ) {
damage -= armour;
}
if (currentHealth - damage < 0) {
currentHealth = 0;
} else {
currentHealth -= damage;
}
}
public static void DamageObject(Collider other, int damage) {
DestroyableObject obj = other.gameObject.GetComponent<DestroyableObject>();
obj.ReceiveDamage(damage);
}
}
What is the issue specifically?
And what is this static function hoping to accomplish here, it doesn't seem to have anything to do with the HealthManager at all so it probably shouldn't be here.
Earlier you were asked to show the console. It is possible to hide logs, so that could be the reason too
SetHealthToMaxHealth and ReceiveDamage do nothing. The variables you're operating on (eg. currentHealth you set to 0) are copies of the variables you passed when calling the method
Their new values will be discarded when execution exits the methods
That's what I was trying to ask exactly but my english won't help me, how should the logic for systems such as this be handled?
Does anyone know why I can't drag muliple audio game objects from the Hierarchy window to the Project windown in Unity 2018.1.9f2? I am trying to create prefabs of audio to put in assets bundles for VAM. All the documentation for Unity says I should just be able to drag muliple GameObjects into the Project window from the scene and it will make a prefab for each object. I get a red circle with a slash that indicates this action is not allowed. I can only drag one object at a time.
My intuition tells me that i should somehow pass a reference
Example of the faulty system:
void A()
{
int health = 100;
Damage(health, 10);
Debug.Log(health); // -> 100, because when passed to 'Damage', a copy of the value is made.
}
void Damage(int health, int damage)
{
health -= damage; // edits a copy of the variable
}
You need to have the current health and armor as class variables instead, to fully separate them from the other scripts
It's possible to pass-by-reference, but for a fully composition based model, the variables related to health must be offloaded to the health script
@short hazel How could I offload variables in a manner that would allow the HealthManager script to be reusable?
I think doing something like GameObject.find("Player").GetComponent<Player>().health is not the right answer.
You'd have a Player script and a Health script aside on the same object
Then Player could serialize a variable of type Health, so you can drag-drop the health script onto the player script, in the Inspector
public class Player : MonoBehaviour
{
[Header("Combat Stats")]
[SerializeField] private int currentHealth;
[SerializeField] private int maxHealth = 100;
[SerializeField] private int armour = 33;
[SerializeField] private int damage = 25;
[SerializeField] private HealthManager healthManager;
void Start() {
healthManager.SetHealthToMaxHealth(currentHealth, maxHealth);
}
void Update() {
if (Input.GetKeyDown(KeyCode.F)) {
HealthManager.ReceiveDamage(55, currentHealth, armour);
}
}
So it should look something like this?
is the most lightweight way to implement BFS a queue?
oh actually it does not make sense because I would still be passing a value.
Good start, now you can move these directly in the HealthManager class:
And the armor if it makes sense
But what if I would want to reuse the HealthManager for an enemy (that has different values. E.g: maxHealth = 200)
Then you go in the enemy's inspector and change the value to 200
It's a separate script instance compared to the one on the player, which will stay at 100
Ohhh right because it's a serialize field. Okey, I finally understand it.
Thank you a lot!
The 100 you set in code is the default value that will be set when you attach the script for the first time. Once you modify it in the Inspector, it's not used anymore
Inspector takes precedence over values set in the code (for field initializers like you have here)
Wait, actually can you reference a script through a SerializeField? or the only way is through getComponent<>()
Yes, that's how you should be doing it
Does HealthBar have a HealthBarScript on it
it does
Then you are referencing the HealthBarScript
oh, thanks
I believe so, yes
how would I set the players orientation equal to the slope they are standing on while still keeping them going in the same direction? transform.up = slopeInfo.normal + new Vector3(0, playerCam.eulerAngles.y, 0);This is what I have right now and it resets the player to the axis of whatever part they're standing on
Without getting into shenanigans
is it possible to get the y value of a rotation for 1 frame and not have it update after?
yes, just store it in a float
like this? float prevLookDirection = playerCam.rotation.y;
well technically yes based on what you asked, but imma go ahead and assume this isnt what you want. A rotation is a quaternion, quaternion values arent gonna be what you expect so you probably want the euler angles
What's the easiest way to check if any particular bounding box is in a cameras view frustum, with no regard for efficiency?
I'm trying to learn the new input system, is there a significant difference between messages / events?
afaik, Messages look through a bunch of classes for a method of a specific name
an event is a delegate. When the delegate gets invoked by myDelegate?.Invoke();, any function added to the delegate gets called
think of a delegate like a list of functions. You add/remove functions from this list, to change what gets called when .Invoke is called
make sense?
example:
public event Action OnJumpButton;
I can add:
OnJumpButton += Jump;
OnJumpButton += SelectMenuItem;
OnJumpButton += MakeJumpSound;
ā¦.
OnJumpButton -= Jump;
OnJumpButton += Swim;
delegates are fast because you are giving the delegate all the deets of what to call before it needs to get called. Messages need to sift through to go find targets. Delegates donāt have the searching bs
Actions are delegates, btw
event makes it so you can only +=, -=, and .Invoke it
Are there any specific factors to be taken into account when choosing for which behavior to go for? As I've read through the documentation and also your explanation I have a feeling that the events system might be a better fit for more robust games.
it is
I only use messages when Unity forces me to, because of OnCollisionEnter/Exit
also, when you ctrl+R to find all references (to find everything activated by a specific message), good luck. That shit doesnāt work because itās just a bunch of different functions that just happen to have the same name in different classes
with delegates, you are calling += etc on that one variable. So Ctrl+R to find all references directly takes you to all the different scripts that are getting triggered
i cannot stress enough how huge that feature is
Okay, i figured this out with GeometryUtilities. It returns true if any part of the bounds in in the camera frustum, which is great, but how can i check for when the ENTIRE bounds in contained within the frustum?
InputSystem is a more complex use case because you are also playing with parsing InputActionCallbackContext objects
but the core of delegates is simple
Do you happen to know of any good resources that covers how to implement the new input system w/ events?
i learned from youtube. and it was painful
there are many tutorials tho
I recommend you try out basic event delegates first
Have you used a button in unity before? And set up the OnClick callback?
It's quite similar to that
You just get a CallbackContext instead of something you explicitly pass.
And the Context is a struct with values
General workflow:
using System;
In Class1:
public event Action<int> OnEvenNumber;
int i = 0;
void Update() {
i++;
if (i %2 == 0) // if i is even
OnEvenNumber?.Invoke(i);
}
What are events? 
I've been using delegates and never really quite understood events.
The docs just say you subscribe and then stuff.
Not yet sadly
Class2:
void PrintMe(int i) { Debug.Log(i);}
void Start() {
GetComponent<Class1>().OnEvenNumber += PrintMe;
}
those two classes together will, every frame, increment a number in Class1, if it is even, it invokes delegate, Class2ās PrintMe method gets called on that input, and it prints that number
Action (no <T>) just takes no arguments
understand?
events are delegates where you only allow +=, -=, and ?.Invoke()
I kinda get it, they should hire you to write the docs imo
Is there a simple way to wait for a UI button onClick event to trigger in a coroutine? E.G.
private IEnumerator doStuff(){
//do stuff
yield return new WaitUntil(/*Wait for the ui button press onClick to fire*/);
//do more stuff
}
I looked online, couldn't find much. Help is appreciated thanks!
Really would rather not keep a bool that gets turned true when the button is pressed... seems inefficient and messy

Thank you!
So I can just encapsulate and it'd be the exact same thing? 
Essentially.
event allows fewer things than normal delegate
a normal delegate lets you fuck with the list of methods in multiple ways
events force that to not happen
so you donāt need to worry about one random class totally fucking up the delegate
if you have only been doing +=, -=, and Invoke(), then it would be interchangeable
event is a modifier
you can have public Action myAction1; and also public event Action myAction2;
itās like a public/private access modifier almost. applying the event keyword blocks several things from being allowed
but itās only blocking because you are telling it to block it, and not because it canāt do it.
Why the hell did the docs go through saying it's a subscription thing and didn't really mention the differences between a event and a normal one that much? 
+= is called subscription
-= is unsubscription
you (un)subscribe functions to the delegate
delegates just have a lot of terms and shit that make them harder to learn
there are events, actions, delegates, functions, lambdas, subscription, and unsubscription. And some of these are similar, but slightly different
Actions and Funcs are just types of delegates. Events are a programming pattern.
No
They do have some kind of linked list internally though
they donāt count as a collection, but they function as a collection where you have zero access to the contents
you canāt know how many, you canāt do any sort of indexing. You canāt even guarantee any sort of sorting (thatās not in the spec)
they are a collection in the abstract sense where they function as a container of functions
but you donāt get things like .Contains, delegate.Count, delegate[5], delegate.Sort, deegate.Concatenateā¦. none of that is a thing.
the delegates are chained together through magic šŖ
if anyone has info on how they're currently chained id love to know as well. I only heard of some implementation that existed 10 years ago
as far as we understand, the critical thing is that ordering within a delegate is not a part of the spec
so if you need A to happen before B, and both are in the same delegate, you canāt actually enforce that order
i would go with the bool you said was "inefficient and messy". Its a bool, it is neither inefficient or messy.
A string based search for IsInvoking is DEFINITELY messy
How does the == operator work?
it does whatever it is defined to do
it needs to be implemented on a class-by-class basis
Nah, delegates are method references. What you're talking about is that they can be chained (linked) together . . .
they feel like a collection of functions, without actually being a collection
How is it a string based search? It's a built in function in Monobehaviour. And yes it is messy to have a bool for everything in my opinion. Hurts readability for me
^i'm not using the parameterized method
yield return new WaitUntil(() => myButton.IsInvoking());
https://docs.unity3d.com/ScriptReference/MonoBehaviour.IsInvoking.html
hm i only saw the first declaration, i see now the one without any params
@static cedar You're thinking about the multicast delegate. I believe it overloads the += and -= operator where they add to an internal collection . . .

The methods are invoked in the order they were added . . .
youāre confusing her
basic vanilla delegate is like a bucket of functions. You throw functions into the bucket (or pull them out), and call them all at once
they technically have an order, but order isnāt a part of the language specification, so that COULD change at any time
you should not depend on the order, yes
they keep an internal collection, but that is an implementation detail that you do not get access to
itās like a black box. you donāt get to look inside
I want to make a elevator that will move up to a set position, Should i use Animation or .movetowards, to prevent issues with the player following the elevator, or the camera bugging?
MovePosition and MoveTowards
the important question is: how does the player move?
elevator should probably have a kinematic rigidbody
Using Rigidbody, but i want the player to move with the elevator.
Ok thanks
is player dynamic or kinematic rb
A kinematic rigidbody elevator ought to be able to push the player correctly, then
Assuming the player is not kinematic.
Make sure that you're only moving the elevator via the rigidbody
so .movetowards wont work?
making objects ride other objects can be hard as shit depending on the scenario
well, without context, I can't answer that question
MoveTowards is a vector operation
all that MoveTowards does is produce a value between two points
MoveTowards just helps you calculate a vector position. By itself, MoveTowards doesnāt actually move anything
it does not intrinsically do anything
Should i just go the route of faking the elevator moving, using a courotine?
if you use rb.MovePosition(pos), where pos was calculated via MoveTowards, that sounds fine
ok
I see nothing fake about doing that
Especially since the elevator is kinematic
you certainly wouldn't want to physically simulate how an elevator works lol
I mean, not moving the elevator at all, and opening the doors after a set amount of time.
ah
that is also reasonable
Also a convenient place to put scene loads, if your scenes are big enough to require a load time
i would only recommend that for a Luigiās Mansion 3 elevator, where it is actually just a loading zone between levels
I'll just do that to resolve any issues, i might run into.
That's not how real elevators work? š¤Æ
elevators are an inside job
I know, which is why i wanted to do the real thing at first.
i was joking
no he wasnāt
oh
Alex Jones told me so
he also explained to me the benefits of his amazing āManJuiceā true energy supplements, with real bits of man in every bite
Fightmilk
they just rebuild the entire building around you while you aren't looking
i knew it
the annoying part is when we have to rebuild the whole country when you get on a plane
gotta keep the round earth myth going
What if, everything you aren't actively looking at isn't rendered, like in a game?'
What if everything behind you, doesnt exist, until you look?
thatās a real thing
What if somebody that your playing online multiplayer(in real life) with is, looking at things you arent looking at. Does that mean that what they are seeing doesnt exist to you, or does your system, have to work harder to render everything?
your system doesn't render what the other player is seeing if you're not seeing it also
Rendering is always client side. You only need to render whatever your client needs to see.
i mean in real life though?
Why are we considering real life?
Sometimes, it needs to happen.
If a tree falls and nobody is there to hear it, does it make a sound?
this is just solipsism in a trenchcoat
Wdym? Real life multiplayer? Are you asking about wether we live in a matrix or something? Lol
check the profiler.
Yea
Probably the wrong place to ask these questions then. And I don't think anyone knows the answer anyway.
Is it developed in Unity? Does reality pay runtime fees?
Does a blind person, live lag-free, since nothing is actually being rendered, its just a whole bunch of audiosources?
Okay.
Lag doesn't just affect rendering though. It affects sound and physics as well.
"God doesn't pay runtime fees" - Albert Einstein
we should probably steer back to something on-topic
What on earth does this have to do with code or Unity
"Pirating is free." - Sun Tzu
Talking about pirating in a GAME DEVELOPMENT server is actually crazy š¤£
Ok i'm done
Seems legit.
Wait, Unity uses Box2D for 2D physics?
Yep
public void OnPointerClick(PointerEventData eventData)
{
Vector2 localCursor = new Vector2(0, 0);
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RawImage>().rectTransform, eventData.pressPosition, eventData.pressEventCamera, out localCursor))
{
Texture tex = GetComponent<RawImage>().texture;
Rect r = GetComponent<RawImage>().rectTransform.rect;
//Using the size of the texture and the local cursor, clamp the X,Y coords between 0 and width - height of texture
float coordX = Mathf.Clamp(0, (((localCursor.x - r.x) * tex.width) / r.width), tex.width);
float coordY = Mathf.Clamp(0, (((localCursor.y - r.y) * tex.height) / r.height), tex.height);
//Convert coordX and coordY to % (0.0-1.0) with respect to texture width and height
float recalcX = coordX / tex.width;
float recalcY = coordY / tex.height;
localCursor = new Vector2(recalcX, recalcY);
CastMiniMapRayToWorld(localCursor);
}
}
private void CastMiniMapRayToWorld(Vector2 localCursor)
{
Ray miniMapRay = GameManager.Instance.minimapCam.ScreenPointToRay(new Vector2(localCursor.x * GameManager.Instance.minimapCam.pixelWidth, localCursor.y * GameManager.Instance.minimapCam.pixelHeight));
RaycastHit miniMapHit;
if (Physics.Raycast(miniMapRay, out miniMapHit, Mathf.Infinity))
{
//Debug.Log("miniMapHit: " + miniMapHit.collider.gameObject);
GameManager.Instance.cam.transform.position = new Vector3(miniMapHit.collider.gameObject.transform.position.x, GameManager.Instance.cam.transform.position.y, miniMapHit.collider.gameObject.transform.position.z-4);
}
}
im using this code with OnPointerClick so that when i click my minimap it's repositioning the player's camera. it works as i want it to but id like to make it so that when im holding the mouse button down over the minimap i could drag around and move the camera that way too.
what's the best way to go about doing that?
Maybe IDragHandlerš¤
{
if (Input.GetAxis("Vertical") > 0)
{
myT.position += myT.forward * movementSpeed * Time.deltaTime * Input.GetAxis("Vertical");
}
if (Input.GetAxis("Vertical") < 0)
{
myT.position += myT.forward * movementSpeed * Time.deltaTime * Input.GetAxis("Vertical") * 0.5;
} ``` so im making a thrust thing obv and when you go backwards its slower but the game doesnt like me putting * 0.5, any idea why?
0.5f
alr ty
is it just a matter of putting the same code from OnPointerClick in OnDrag? i tried that and doesnt seem to be working
OnDrag has a few different interfaces
i included drag start and end, but not sure if anything needs to be in them
One thing to note is that only one event is triggered per frame
OnDragStart is a single event, but I think you can pretty much use onpointerclick too for it?
Not everything needs to be used, but OnDrag is pretty much the main event which should contain the repositional logic.
Ah, actually OnDragStart doesn't trigger until you hold down the mouse and move a bit
private PointerEventData _pointerData = null;
private void Update()
{
if (_pointerData != null)
{
OnPointerClick(_pointerData);
}
}
public void OnPointerDown(PointerEventData eventData)
{
_pointerData = eventData;
}
public void OnPointerUp(PointerEventData eventData)
{
_pointerData = null;
}
i tried this too but this doesnt work, curious how come that is
Why doesn't the coordinate logic there work in OnDrag? I would assume it works similarly as OnPointerClick* would be called at your pointer position every frame instead of needing to click.
Texture tex = GetComponent<RawImage>().texture;
Rect r = GetComponent<RawImage>().rectTransform.rect;
This would be set at OnStartDrag probably
And then OnEndDrag you can probably ignore or unset everything being used
Is it worth it trying to build a nice platformer player controller using RigidBody2D?
If you want to use unity's physics system you go with rigidbody2D
otherwise you're implementing logic like gravity and stuff
Yep, I am trying to build a nice player controller rn, but my player feels like he is falling through viscous liquid, increasing mass hinders movement on the x-axis, increasing gravity also has some similar affect.
You're setting velocity then, right?
yep
What are you setting the Y value to?
You could also do AddForce if you'd rather btw,
Which is also Rigidbody based movement.
experimenting between 700-800
Wut...
speed...
Maybe show the code?
That is wild
Wait... are you multiplying it by deltaTime?
Because you should not be
Going through docs seeing AddForce and velocity.
haha
Ok yeah... get rid of deltaTime
You'll have to reduce the speed a lot
And then, you are also setting the y value to 0 sometimes actually
player just became Flash
GetAxisRaw will return 0 when you aren't giving input. And 0 times your speed is obviously 0. So you are repeatedly setting velocity to 0 when in the air, which explains the "viscous fluid" feeling
You should do a ground check, and when not on the ground, set the velocity to a gravity value like -9.8
righty got it, docs are a bit disorienting, figuring things out,thanks a lot for helping, I have used Raylib before which is very simple and everything that moves is multiplied by deltatime.
Yeah, you want to use deltaTime in a lot of places, but deltaTime is ALREADY used in AddForce for multiple modes, and Velocity is in meters per second, so it already uses time.
But if you were using transform.position += someValue, you would want to scale that with deltaTime
Basically, unity does the work for you with AddForce and velocity haha
yea, did that last time when making pong, collisions got fucked up and I had no idea why.
Oh yeah, that bypasses physics and can cause that issue. It's basically It IS teleporting
Again, tho, is it possible to make a good player controller using RigidBody2D?
I watched Tarodev's video on the topic and it really looks noice.
https://github.com/Matthew-J-Spencer/Ultimate-2D-Controller/blob/main/Scripts/PlayerController.cs
yes, you can . . .
anything you can point me towards that achieves that besides documentation?
not that i recall. you need to determine how you're going to move: set velocity, add force, or the Move methods (kinematic rigidbody). each have their pros and cons. i'd look up videos, controllers, or references on those first . . .
righty
hey how can i get autocorrect is vs code
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
its not working
Hey guys, Created this here to control my ship animation.. it is working but the prob is that if I click to fast right and left sometimes it doesnt register and the animation doesnt happen.. anyway to fix that?
Don't set Turn_Right false when you release left button and vice versa
will try it thank you
That fixed, thank you
š and don't cross-post in the future
[RequireComponent (typeof(RigidBody))] what did i do wrong?
You spelled Rigidbody wrong
please help with that
Please provide more details on what you tried. Just saying "it's not working" does not help
Configure your !ide if you're not getting autocomplete and error highlighting
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
is it possible to add a baked lightning map to an object I am instantiating?
(or instantiate them with the map already)
Hey guys. Does anybody here know how to call a function from a script from another script without using tags?
@gusty lagoon is the object containing the 'target' script dynamically created or always in the scene?
Consider using the steps specified here in order to determine the best way to reference your scripts.
im not getting the errors
i made mistsakes but idk where
Is it okay to have 2 canvas assigned in 1 camera?
Yeah, having multiple canvas is pretty standard.
trying to use Physics.SphereCastAll but in the editor it's telling me my starting pos needs to be a ray and in the documentation they have a whole bunch of parameters I have no idea what to do with. namely Direction. anyone know how to use this?
There are several overloads for the method. One of them takes a ray. Some other take origin and direction. Choose one that suits your needs.
Hey I'm currently working on a house building system. How can I make sure that the buildable object will only be placed when its not clipped into the wall? And any solutions for the buildable incline issue while the cursor is on the wall?
I'm trying to use the pos one
it just won't let me. guessing I need more variables but idk what they are nor what value of them I need
Since you already project the object into the scene just add a collider on the sides and check if touches something.
What variables do you not know about?
It touch each other
it should be one of these
Use layers.
And make the layers not interact then.
Sure so if the wall touch the buildable, it shopuldnt be placed?
They're all self explanatory. Which one do you have trouble understanding?
direction
Does this need an rb?
Yeah add a box collider with trigger enabled that is a bit larger than the object, and then if that collider is triggered make it not being able to be placed.
Direction is the direction in which you want to cast your sphere.
like, no idea what direction it wants. why does it even need a direction
do I just say vector3.left?
What direction do you want?
And then make it so that the collider for checking only interacts with the correct objects.
no idea xD
With what function? OnTrigger?
I don't care about the direction
If you have no idea, then why even do the cast?
I just need to get all objects in the sphere
Hello guys. How can I get the same behaviour as in "GetAxis("Horizontal")" with the new input system?
I don't want it to jump instantly from 0 to 1 and -1 but rather to go smoothly.
Yeah OnTrigger put a boolean to true and OnTriggerExit put it to false.
Then you're using a wrong method.
Use OverlapSphere instead.
And then something like: if (isTouchingWall) return;
ah
sphere cast goes in a direction
Sphere cast is like rolling a ball in a direction.
oooh
This is the current setup
that explains why I was confused. thanks
I thought a spherecast was just a spherical raycast
@copper pumice I want to recreate the behaviour that "GetAxis" has but with the use of the new input system.
it's more related to the standard raycast while overlap sphere is for a general area
Today I found out that there was actually a hack for this. Just click on any object in the heirarchy, then spam Alt+Left arrow
Sorry, so each of the walls should have the scipt? or the buildable should be a trigger?
I've done this
It is. What you're referring to is not a spherical ray cast, since it doesn't cast anything anywhere. You just want to check if anything is overlapping a sphere.
and it doesnt work
so I'm not fully understanding casts in general 
use GetMask
also check if the code even work without the if check
A raycast is like moving a point through space. You "cast a ray". A sphere cast is like moving a sphere through space, thus sphere cast.
actually idk if getmask will work too
so it's just a raycast with thickness?
With a radius, yes.
knowledge has been obtained, thanks
It should be given to the gameobject with the collider
And I actually meant to change it so that the layers only interact with each other in settings, not with an if statement. But that should probably work too. Check the layer spelling and make sure that the correct objects has the layer enabled. You can always try tags instead.
I did it with oncollisionstay, now it works
what do you mean?
You can change it so that only certain layers collide with other layers in the physics settings
I know that
Hey, I'm trying to set a single component of an object's rotation without changing the other components. I don't want to change the rotation incrementally (i.e. with RotateAround), I want to directly set the value.
I've been trying this:
void SetRotation(float angle)
{
transform.localRotation = Quaternion.Euler(angle, transform.localEulerAngles.y, transform.localEulerAngles.z);
}```
but I'm getting some strange behaviour when `angle` is greater than 90 degrees (the angle flickers between being greater than 90 and less than 90). I've read that reading from `transform.localEulerAngles` is a bad idea, but I haven't been able to find an alternative solution. Does anyone have a better way to do this?
If you hold shift while doing the alt arrow command, it'll open and close all. It also works in the project tab as well.
for some reason, holding shift prevents me from closing anything else than what gameobject is selected
Maybe it's just shift and no alt. Im not here to test it. I use it all the time but it's second nature that it's just muscle memory.
Iirc it's just alt, not shift at all
It is now because I'm confused and need to know what I've been doing. But that's hours away from checking. Lol
yea, left arrow can do it alone, alt speeds it up
Is there a way to tracj which objects are enabled and disabled in a parent and save this?
Anyone have any resources they could point me twoards, to editing a sprite shape via runtime? I know I could grab each spline point, and have a handle the player could move, however, adding new points is I'm not sure?
Sure. Loop the children and cache their state in a bool list or something.
ah, yeah that should do it. Thank ya š
How can I fix this error. WARNING:We recommend using a newer Android Gradle plugin to use compileSdk = 33
It's a warning, not an error
No, it's a warning. Those errors are caused by something else. Post the full error message to #š±āmobile
Just to make sure, if I for example do otherScript.someArray = this.someArray; and then do this.someArray[0] = 7;, then otherScript.someArray[0] == 7; right?
yes, arrays are reference types. so if both variables reference the same array instance then modifying the elements of one of those variables will affect the array referenced in both variables.
however you cannot assign a new array instance to one variable and expect the other to be affected
Alright, thanks!
Assigning to a variable will only affect another variable if your variable is a ref
well, or out, I guess
Hey Loha, there is a small angle transformation you need to do in order to make it work. I don't know what you trying to achieve but when working with euler angles very often you have to do something like eulerDir.x -= eulerDir.x > 180 ? 360 : 0; .
Directly manipulating individual euler angles can be difficult.
as you mentioned
However alternative way, which I use more often is not working directly with euler angles but rather setting the transform.foward to the right direction. Basically you find a direction to the target by doing (targetPosition - originPosition).normalized and then set it to e.g. transform.forward
Yeah. That can often behave better.
hello guys ! hello can i force a moving gameObject to stay at a certain distance of the ground ?
Not much information in your question to be honest. You could do it many ways, just giving it a collider would be one of the easier ones.
without physics* sorry
like i have a 3d object that can climb on walls (its a spider)
but i want it to stay always at the same distance of its ground
is it dynamic or kinematic?
uh⦠it has no collision at all?
ok, then youāre going to need to raycast or spherecast to move around
its already moving and climbing walls
it would maybe be easier to give it a kinematic rigidbody and set its layer to ignore raycasts
i just want it to stay a certain height of the ground
i could put a collider without a rb tho idk, my professor doesnt want physics in the project
that way nothing can interact with it, but the physics system can smoothly move it from point a to point B
its already moving hello u read what i write šš
its already moving and climbing walls
i just want it to stay a certain height of the ground
i could put a collider without a rb tho idk, my professor doesnt want physics in the project
To sum it up
what I mean is if it has a Kinematic RB, you can tell it to MovePosition once per physics frame
and the physics system will figure out where to put it in between for every frame
makes sense?
it does
but doesnt solve anything, ive already been through that
gravity fucks up the whole thing
gravity has no effect on kinematic RBs
if i put gravity, it cant work, if i remove it, it doesnt work too
oh yeah
kinematics one mb
but a rb would just make my spider fly
does the spider climb walls?
it walks on everything
Hmmm, silly question but cannot you simply raycast downwards and check the distance between spider's position and the hit position?
for the 4th time,
that means he needs to define down
-transform.up
he needs to initialize to a certain snapping direction
exactly
i can, but i cant say "trasnform.pos = upRay(8) from this hit pos)
bc it wouldnt move
then spherecast to look around
yeah, I think the pieces all make sense now
so what is the part you have trouble with?
you can, your movement would have to only prevent movement in the down direction then
when you say it can walk walls but not maintain distance, you mean you canāt get it to keep distance, but it does respect level geometry shape?
or that it does not respect level geometry shape, so if you have a hill, it moves along a plane?
here my spider climbing a cube
and going down on the other side
he is my problem, wrong distance of the ground
yes
oh itās a tetrapod
ok, so right now you use a cast to know where it needs to go, right?
yes its the red rays
that cast outputs a RayCastHit, which has a normal for the surface
yes
and then pouf spider.normal = hit.normal
with a lerp, and more of a rotation but yeah
if you need to translate normal to the surface, then just transform.translate by hit.normal * the distance you need
I think I still struggle a little bit to understand the issue. Do you want to keep the body certain distance from the surface it is walking on or never be able to reach the ground (the blue surface)?
i dont understand which part is confusing
thatās a good question
because that would be an inverse kinematics problem
Can you sent also 2 pictures: one of what is going on (the problem) and the other (in the editor, not in the play mode) how you would like it to look like?
first proposition
body certain distance from surface
maybe its just a translate to do
thats why im in code beginner xd
In that case I believe the simplest way would be to do as you say simple translate. You could simply do transform.position = targetPosition + (transform.up * distance)
actually maybe not so hard, if you solve the body first
not hard if you are okay with it looking janky lol
use this with casting to move around the body. Then the hard part is solving the positions of the legs as it walks
whats hard
yeah, this is a hard problem if you want it to be accurate
because it isnāt a simple object
itās a tetrapod
it is
the four legs move with the body
the legs follow the body, i just need to touch to the body
the controller moves my body and the legs follow by themselves, procedurally animated
so if you want it to be accurate, you need to solve the motion of the whole thing like a robot
i've that rn
i just want it
to be at a the right distance of the surface its walking on, thats all
then i just need that
making the legs match up to accurately move everything in a way that makes sense is the hard part
ITS ALREADY DONE š
so yeah, just use some spherecasts, bro

