#💻┃code-beginner
1 messages · Page 148 of 1
Did you try looking up how to get mouse position in the new input system
so im making a flappy bird ish game to learn unity because i just started today. and my UI works for getting points when you go through the pipes. but after 9 it goes to 1 instead of 10. and after 10 it goes to 2 instead of 20. how can i fix it so it shows the whole number?
Make your text are bigger or make the font smaller
I just reused the same code taht I already used earlier for the camera movement of the player.
But instead of:
Vector2 targetMouseDelta = _controls1.Player.Camera_Movement.ReadValue<Vector2>();
I changed it to:
var ray = _camera.ScreenPointToRay(_controls.Player.Camera_Movement.ReadValue<Vector2>());
Neither of those are mouse position
i also have another problem where it adds a point to the score even after the game over if it goes through the objects
If I use:
var ray = _camera.ScreenPointToRay(Input.mousePosition);
I get this Error:
UnityEngine.Input.get_mousePosition () (at <7b7960ce51044497a5379ae0d5d70e62>:0)
SoulShardsCollecting.Update () (at Assets/Game/Scripts/SoulShards/SoulShardsCollecting.cs:
Seems pretty self explanatory, no?
Did you try looking up how to get mouse position in the new input system
self explainging in case of that its not compatible with the new input system.
But no clue how to replace it with something compatible...
make an input action bound to mouse position and read the value from there, muhc like any other input in the new system
OR
directly read from the mouse device e.g. Mouse.current.position.ReadValue()
yes, then I landed there and their solution was claimed as wrong aswell:
worldPos = mainCam.ScreenToWorldPoint(Mouse.current.position);
further down in the same thread https://forum.unity.com/threads/mouse-position-with-new-input-system.829248/#post-6739015
that first person just forgot to write ReadValue() is all
Thankfully there's more than one site on the internet
anyone knows anything from mirror i am trying to implement some networking in my game but it gives me an error
void CmdPlayerShot (string _playerID, int _damage)
{
Debug.Log(_playerID + " has been shot");
Player _player = GameManager.GetPlayer (_playerID);
_player.RpcTakeDamage(_damage);
}
These answers with false suggestions at the beginning are very misleading. Especially when this forum discussion goes on for so long.
But at least it works now. Thanks @wintry quarry @polar acorn
//This here finally worked!
var ray = _camera.ScreenPointToRay(Mouse.current.position.ReadValue());
Assets\Scripts\PlayerShoot.cs(115,17): error CS1061: 'Player' does not contain a definition for 'RpcTakeDamage' and no accessible extension method 'RpcTakeDamage' accepting a first argument of type 'Player' could be found (are you missing a using directive or an assembly reference?)
Looks like you're trying to call a function that doesn't exist
On line 115 of PlayerShoot.cs
yeah but when i call a script with namespace do i need to call a script that is attached to it also with namespace or how does this work
this has nothing to do with namespaces
completely irrelevant to your error
you're just calling a function that doesn't exist/you never defined
because i added namespace and now it is fixed but i get other error
Assets\Scripts\PlayerShoot.cs(115,30): error CS0029: Cannot implicitly convert type 'Mirror.Examples.Basic.Player' to 'MirrorBasics.Player'
You're using two different Player classes
Cannot implicitly convert type 'Mirror.Examples.Basic.Player' to 'MirrorBasics.Player'CS0029
PlayerShoot is using Mirror.Examples.Basic.Player and the Player class is using MirrorBasics.Player
make sure you use the same one in both places
is there a way i can easly change this
they are in both scripts the same
doesn't sound like it
sounds like you have using Mirror.Examples.Basic; in PlayerShoot and using MirrorBasics; in Player
but I'm really just guessing here based on the errors since you haven't shared your scripts.
void CmdPlayerShot (string _playerID, int _damage)
{
Debug.Log(_playerID + " has been shot");
Player _player = GameManager.GetPlayer (_playerID);
_player.RpcTakeDamage(_damage);
}````
this is the one giving error
As I said, the using directives are the problem
also your GameManager is also likely involved here
it's returning the wrong type of Player
you really need to decide which Player class you want to use, and consistently use that across all your scripts
using System.Collections.Generic;
using Mirror;
using Unity.Mathematics;
using UnityEngine;
using Mirror.Examples.Basic;
namespace MirrorBasics {
Exactly as I said: using Mirror.Examples.Basic;
using System.Collections.Generic;
using System.Numerics;
using Mirror;
using Mirror.Examples.Basic;
using UnityEngine;````
ecept since this class is IN the MirrorBasics namespace it will use the one from MirrorBasics
is there a reason you're putting your classes into random other namespaces?
Is there a way to limit the Raycast without a if statement?
Something like a preset you make and then the ray knows its only 2 meter long instead of checking if a infinity long ray was shorter than 2 meter by hitting the gameobject.
You can pass Raycasts a distance
i was working on netwroking via mirror and the dude i was following said i needed to implement Mirrorbasics namespace in every script
can i just deletete it in these scripts
but how?
I tried to look but there isn't anything that works or makes sence.
It always let me show results with a if statement as a lenght check.
That link, maxDistance.
there's no reason your scripts need to be in any particular namespace
but again you need to decide which of the two Player classes you want to actually use
is there a code example with "maxDistance"? Because the examples I see bellow is just another if statement again.
Yes it's on the page
you want to avoid using an if statement, but the if statement is not used to limit the distance, it is used to query the raycast for the hit
you can just Raycast() but then you will need to check if the hit has anything in it, with an if statement
if (Physics.Raycast(ray, out hit, 100))
Debug.DrawLine(ray.origin, hit.point);
becomes
Physics.Raycast(ray, out hit, 100);
if(hit.collider)
Debug.DrawLine(ray.origin, hit.point);
Raycasts and Ifs are 🤞
How you find this always so fast?
Because I'm reading this page for the 5th time and I'm stil dont see a "maxDistance" somewhere in the code.
I always find this if statement with Physics.Raycast...
ctrl + f on the page
In the example, the maxDistance is set to infinity
Because you don't put the words maxDistance in the code it's a parameter
is there a way to only set the maxDistance to the Raycast without all the other bunch of parameters to?
yes
by setting that parameter
and not the others
How does it know what parameter is what if I only write float 1f in there?
Because of which parameter you have entered 1f for
the example I see is:
public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layerMask, QueryTriggerInteraction queryTriggerInteraction);
public static bool Raycast(float 1f); //is the smaller alternative```
Where are you seeing a raycast that takes only a float parameter
- raycast.
- where?
- doesnt matter just do it
- raycasting from UNKNOWN towards UNKNOWN for 1 unit
public static bool Raycast(float 1f); makes no sense, but how you should set only the maxDistance without the others?
you don't
you have to give it all required parameters
if you don't need any other optional parameters, don't include them
do you know what method overloading is?
"I do not know who I am
I do not know why I am here
all I know is I am 1 unit long"
"why am i here? "
"to hit something no further than 1 unit"
heres a basic one, u got a position, a direction, and a distance
no more, no less
The example shows:
public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layerMask, QueryTriggerInteraction queryTriggerInteraction);
how should I only set "float 1f" for maxDistance without setting values for all the others?
@spring skiff there is an alternative way of finding the overloads you need, click on Raycast method name in visual studio and press F12
it will show you all the defined overloads (variants) of the Raycast method
you can find the one that suits your needs
Don't pass values for the ones you don't need
you need to provide all arguments for the methods unless they are optional parameters
also read the links i sent if you dont familiar with c# oop
i would like an answer, do you know what overload is?
im getting the console logs but im not getting the particle system playing until much later
and i dont know why
The particle system probably just doesn't emit right away. Consider checking the "Prewarm" box, or if you're using bursts, make sure they start at time 0
maybe you should check if its playing already, afair calling Play() restarts the PS, i may be wrong
i stop the sprintpuffs at Start()
your log shows 2000+ messages, it is likely called every frame
its called on update
how should this work?
How should Raycast know that I mean the MaxDistance?
The first one in the () is Vector 3 origin, the second is the direction and the 4th one would be the macDistance. What do I paste in all the others I dont need?
is it "none" is it "null"
if I only write the MaxDistance as only, so how should it know that its the raycast?
I think its marked as 4th area inside of the ()
please tell me do you know what a method overload is?
If you don't need them, simply do not include them. MaxDistance is literally the first optional parameter
You give it all the required ones
then give it a distance
Is there a way to store scriptable objects within scriptable objects?
Or is there a code structure someone can recommend that would be a good workaround?
I basically have a list that holds skills. Both the list and skills are scriptable objects as I want all enemies and players to work off this same system.
subassets
but you are limited to one level and they are not very convenient to work with
One level meaning?
you have any sprites in the project? look at how its structured
texture asset has sprite subasset
you cant have a subasset of a subasset, its only one level
one level.. like.. u asked within
so 1 level.. would just mean.. the bottom floor..
(1) story
I see
lol. multiple levels .. would be 2 stories.. or (a scriptable object within a scriptable object)
3 levels would be scriptable object within a scriptable object within a scriptable object..
4 levels.. would be.
lol j/k
its limited this way because the subasset has a local GUID, so the full sub asset reference path is parent GUID + local
allowing unlimited nesting would probably kill deserialization and reference resolution performance
recursive scriptable objects!
alternative is to serialize data in the scriptable with SerializeReference attribute or with Odin
with that you can have unlimited graphs
😵💫
but you wont be able to reference serialized objects externally
checking prewarm just glitches it out massively
Ill look into it. But i just thought of... Maybe ill just have a nested script class to store my levels then just have the scripts reference their respective scriptable objects for data
? i wonder why.. prewarm just means its ready to go when u press play.. it shouldnt do anything differently than what it does when its not
ill record
@rocky canyon
when i start my flappy bird clone (haha) it starts immediately, can i make it so that it only starts after the user presses space?
ahh, i see probably has something to do with the way they're spawned.
or.. teh simulation space? idk tbh never seen that happen
i turned down the duration to 0.5 and it worked for a bit but like
particle systems seem to be a real pain for me
ya, they're just something u get better at the more u tinker with them..
VFX graph is even more powerful than the built in Particle System and is complex too..
but with VFX graph you have more fine-control over your particle systems
i have a student plan so i saw that i can use the multiplayer of unity for free is there any tutorial on how to set it up?
you can make an intro scene which loads the game scene on space
or if you want to make it all in one scene, you can start with Time.timeScale = 0, and set it to 1 on space
last is dirty and may lead to problems
i just dont understand why this happens
cclicking on the player seems to fix it
🤔 ill do a bit of googling on the side but i have no idea
appreciate it, let me know if you have any ideas 😄
i was going to work with my particle systems today anyway.. so may work out
it is fate
i usually just use pre-made visual effects
but for something like a dash, i'd probably make my own.. b/c for something like that i'd probably use the distance stuff.. like after moving so far u spawn a puff.. etc
Rate over distance thats the one
well either way appreciate the rewsources
lol no worries.. i saw ur art style.. figured those might be useful to u
i love stylized vfx
it was a bit too hard to get everything consistent so i didnt bother
are you talking about the things on the ground?
or
the cloud puffs the one ur having issues with
oh i made them myself
ohhh okay okay, nvm then
and they just spawn continuously like during a boolean being true?
basically, its just a normal particle system
i can give you a package if u want
and this is the only code controlling it?
should be, yeah
no worries.. i can make something myself real quick with just some circle sprites
i was having issue with other particle systems in my game where it wouldnt start and start super late or whatever
i guess just the particle system control was the hardest part
i'll remember ur issue as i work on my particles.. if i find a solution or think of something ill let ya know with a ping or something
thanks man much appreciated 😄
ill look into it thank you!
hey guys. im trying to set up assembly defenitions for my project but ive encountered an issue.
i cant refrance the c# class generated by the input system for my input action maps(its called Player_InputActionMap)
in the input action map as you can see i set the namespace to UnityEngine.InputSystem, and all the scripts that have a refrance to Player_InputActionMap also have a directive to UnityEngine.InputSystem which is also included in my asmdef. but for some reason i still get this error. how can i fix this? am i doing something wrong?
Why is your generated C# class in the UnityEngine.InputSystem namespace?
Anyway namespaces and assemblies really have nothing to do with one another
then how do i refrance it?
it depends where the code lives and where the code that is trying to reference it lives
e.g. which assembly definitions they are inside, if any
Where is the code that wants to use this class? What asmdef is it in?
Where is this class defined? What asmdef is it in?
this also dosnt work
again namespaces have nothing to do with assemblies. They are simply part of the name of the class
again you're looking at namespaces
which are not relevant to the assembly issue
so if my input action class is in the folder that my asmdef is in it should be fixed?
^^ You have to add the reference to the DLL in the asemdef file
it depends where both classes are
if you put them in the same assembly, sure then it will work with no additional steps
so if i put them both in the same folder it should work?
if they are in different assemblies, then the one that uses the other must reference the one it is using
i thought assemblies looked at the namespaces of scripts to check which ones should be included in them, based on the name of the assembly. my bad
thanks
They do not
asmdefs make an assembly that contains all the files in their folder and subfolders.
to reference any scripts outside the assembly, the other code must also be in an assembly and the first assembly must reference the other assembly. Namespaces don't come into play at all.
Of course namespaces still matter in the code but they are just prefixes to the name of the class
e.g. you may either write the full name of the class like UnityEngine.GameObject; or write just GameObject for short if you have using UnityEngine; in your file
arent assemblies mostly useless since a game is gonna have lots of singletons that get referenced from basically everywhere so you cant really have different assemblies?
I don't see how singletons have anything to do with the usefulness or not of assemblies
assemblies are for grouping code into reusable bundles/packages and for speeding up compile times
i thought u cant call methods on a script that is in a different assembly
Of course you can. This entire discussion has been about how to do that.
oh wow TIL. thanks, so assemblies are useful after all
@wintry quarry hey soo uhh that did not fix it...
its placed with all my other scripts
and i still get the error
ohh shi
nvm nvm
sorry for the ping
wait, if you reference a different assembly via an assembly, does that nullify the compile time benefit?
No - the idea is that when you make a change in one assembly, only that assembly must be recompiled and not the entire project.
although I guess it might also recompile assemblies that depend on the one in which the changes happened.
oh so if you're referencing lots of different singletons from every script you have, then changing a singleton will also cause all of your other code to compile again, despite having assemblies
"having lots of singletons" has nothing to do with assemblies, again
Hey, guys! I have a question. How to set my current screen resolution when I am entering the game? So, whenever the player enters the game I want their screen resolution to be default?
Why would every script you have be referencing lots of singletons?
Seems like bad code design in the first place.
not referencing, but calling. using Singleton.Instance.MyMethod(). thats good code design right?
is there a better way to, for example, tell your AchievementManager singleton that you want a specific achievement to be unlocked?
cause lots of different things can give achievements and they could be in any script
Hi! I have an issue with the moving platform. I applied this code but the player stutters when on platform and eventually falls off.
you're teleporting your platform with Translate rather than appropriately moving it via physics
also parenting is not going to keep your player on the platform if it has a dynamic Rigidbody
I put Kinematic
for what
the rigidbody for platform
I understand but I don't know how to make a code out of it
also its not good practice to parent ur player to the platform because theres lots of potential issues that arise from that even if done right
Using https://docs.unity3d.com/ScriptReference/Rigidbody2D.MovePosition.html in FixedUpdate
I still have the same issue, this is what the code looks like now
turn on interpolation on both objects to reduce stuttering.
And again - parenting is not a good idea
what do I replace it with?
instead of using parenting
the entire script you sent earlier?
why am i getting this error in my build?
just delete the parenting business entirely to start out with
see if friction will do it on its own
also try with a custom physic material 2d with higher friction
doesnt happen in my playtest
okay the stuttering stopped but I don't move with the platform
you can either 1. get the platform's velocity and add it to the player,
or 2. you can just see if the player is standing on the same thing as last frame and if yes,
add its position difference to the player's position
(in both cases u raycast down from the player each frame to get the platform by the way)
im not sure which option is better though. what do you think @wintry quarry ?
what's the code on your player look like?
If your player movement code is overwriting velocity for example. it's going to break all of this
yeah thats possibly happening
If you only move via AddForce for example it will behave naturally
Hey guys, I was thinking of implementing a jump slide mechanic, which means if the player tries to slide before landing after a jump, the sliding value would increase. My question is how do I detect if a player has just touched the ground and at the same time wants to slide?
just touched the ground
Can be done with OnCollisionEnter, maybe starting a timer of some kind
Wants to slide
Presumably the intent of the player to slide would be related to some kind of input they are pressing?
ah I see, is OnCollisinEneter a function?
It sure is
or ask your friendly neighborhood AI "How to detect collision in Unity3D"
alr thanks
how do i ignore collsision between two gamobject i cant use layers because its a multiplayer game and i dont want a gamobject to collide with the player that spawned it but i want to collide with other players
thank you
I'm trying to draw sphere gizmo on each face of a cube, it works when I use a cube created in Unity, but not on a custom cube mesh. The gizmo will spawn inside the middle of my mesh cube. What is going on? ```Vector3 spherePosition = transform.position + transform.right * transform.lossyScale.y / 2f;
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(spherePosition, 1);```
The bounds center is also off for some reason
Hello! Im having some issues with a statement. Im getting this error
using System.Collections.Generic;
using UnityEngine;
public class DialogManager : MonoBehaviour
{
[SerializeField] GameObject dialogBox;
[SerializeField] Text dialogText;
[SerializeField] int lettersPerSecond;
public static DialogManager Instance { get; private set; }
private void Awake() {
Instance = this;
}
public void ShowDialog(Dialog dialog) {
dialogBox.SetActive(true);
StartCoroutine(TypeDialog(dialog.Lines[0]));
}
public IEnumerator TypeDialog(string line) {
dialogText.text = "";
foreach (var letter in line.ToCharArray()) {
dialogText.text += letter;
yield return new WaitForSeconds(1f / lettersPerSecond);
}
}
}
This is the code
@ancient scarabUse textmeshpro instead
How do i use that?
Well adjust accordingly if there are any warnings
tyy
And import the textmeshpro package
Is there no other way to fix the existing problem btw?
The existing problem is that you were using Text, which is old and has been replaced by TextMeshPro TMP_Text
Sure, you can still use it (it's not marked as obsolete), but it's better to use the latest tools. For the original error, you were missing a using UnityEngine.UI directive at the top.
In my game, whenever my bullet object hits a wall I'm instantiating a new prefab object with a particle system component to create particle effects. (The object is destroyed after playback) Would it be any better for performance/etc. if I had the particle system component on the bullet object itself? Can't decide between the two approaches
The best way to do this is to have an Object Pool of particle systems, and whenever one is needed, activate it and put it at the impact site. Then, when it's done, instead of destroying it, you reset it and deactivate it so it can be used again
I would not expect making it part of the bullet to matter at all
(other than making your design more complicated)
I was fearing this answer 😔
thank you
the answer might also be "it doesn't matter"
It's not very difficult at all, especially since Unity actually officially added pooling support
with ObjectPool<T> ?
Yeah, much easier that rolling up your own
Same issue but this time its Action..
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogManager : MonoBehaviour
{
[SerializeField] GameObject dialogBox;
[SerializeField] Text dialogText;
[SerializeField] int lettersPerSecond;
public event Action OnShowDialog;
public event Action OnHideDialog;
public static DialogManager Instance { get; private set; }
private void Awake() {
Instance = this;
}
Dialog dialog;
int currentLine = 0;
bool isTyping;
public IEnumerator ShowDialog(Dialog dialog) {
yield return new WaitForEndOfFrame();
OnShowDialog?.Invoke();
this.dialog = dialog;
dialogBox.SetActive(true);
StartCoroutine(TypeDialog(dialog.Lines[0]));
}
private void HandleUpdate() {
if (Input.GetKeyDown(KeyCode.Z) && !isTyping) {
++currentLine;
if (currentLine < dialog.Lines.Count) {
StartCoroutine(TypeDialog(dialog.Lines[currentLine]));
} else {
dialogBox.SetActive(false);
OnHideDialog?.Invoke();
}
}
}
public IEnumerator TypeDialog(string line) {
isTyping = true;
dialogText.text = "";
foreach (var letter in line.ToCharArray()) {
dialogText.text += letter;
yield return new WaitForSeconds(1f / lettersPerSecond);
}
isTyping = false;
}
}
Hover over the error in your code, a light bulb will appear, click it
It'll give you suggestions to fix it
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
Action is in the System namespace
This is my first time using the "new" input system and this is what I have for input in my movement script: https://pastebin.com/BSihe8J1. I am making a separate script for controlling the camera, how can I move the input management to a separate script to avoid getting multiple references to the PlayerInputActions?
There's no problem with getting multiple references to the map
I know, I just wanted to know so I could make my inspector look nicer.
`` [Command]
public void ChangeLanguage(string localeName)
{
var targetLocale = LocalizationSettings.AvailableLocales.Locales.Find(x => x.LocaleName == localeName);
if (targetLocale != null)
{
LocalizationSettings.SelectedLocale = targetLocale;
}
}`` Whats wrong here ?
You tell us
I have the unity thing installed but it doesnt work for some reason lol
There are two steps to the guide:
- Install the workload for Visual Studio
- Tell Unity that VS is the code editor it needs to use
Make sure you followed the guide entirely
OkOk
hi, i need some help to add a code for enemy damage

how do i get a random vector 3 direction within a cone with a certain angle? i want to do this for bullet spread
I followed the guide entirely and it is linked now. It still doesnt give the errormessage though.
Post a screenshot of the code editor
Something like:
Vector3 forward = whatever; // this is the normal aiming vector
Quaternion perturbation = Quaternion.Euler(Random.Range(-angle / 2f, angle / 2f), Random.Range(-angle / 2f, angle / 2f), 0);
Vector3 withRandomSpread = perturbation * forward;```
i dont think you can multiply vector3s with quaternions but ill try
you would think wrong 😉
Ah, VS Code. I don't use that for C# so I can't say. It's definitely not configured as some types like MonoBehaviour are not recognized (not colored properly)
u use VS?
Yes, 2022
as praetor had it
r u joking?
no he aint
The order matters. Praetor did it right
Bigga big L
Multiplication is not commutative in four dimensions
That reply wasn't for you, but glad you fixed it
No i know just wanted to let u know i fixed it 😄
https://gdl.space/vedikozime.cs
Here is the code, someone know why don't the bullets hit the enemy?
you just have a random RaycastHit variable that you never assign to anywhere and seem to expect it to magically detect when some other object collides with anything?
Are you trying to use projectiles or raycasts?
Pick one
if you're trying to use a raycast, it usually helps to actually have some raycast in your code
then you need to actually do a raycast
and i don't understand what the projectile you're spawning is for
the result dosnt come out in a circular pattern. whats wrong?
Why would it be circular? It's random inside a cone, meaning it'd be pretty unlikely for them to form a cirlce
why am i getting t his error? i didnt write "internal". it just says abstract in the script file
Station is likely either internal or private
Is Station public?
If you want it to be public, yes
do you see the picture i sent? what i want is for the direction to be in a random angle, which would look like this, a cone. so if all the shots come out within this cone they should hit somewhere in a circle
it doesn't. your issue is just that you are trying to create a public derived class from a class that is not public. if your derived class was also internal then you would not have received any error
Yeah, so the bullet holes all do seem to be in that circle
noooo, the reason the end of the cone looks like an ellipse in the picture is beacuse its supposed to represent a 3d cone viewed at an angle
like this?
heres another example, i want the raycasts to go in a direction that they would end up hitting somewhere within that blue circle, the base of the cone
Yes, that's what I assumed. The bullet hole clusters seem like they could come from this sort of spread
but the bullets keep landing like this
Your code has you randomizing XY, maybe what you need is ZY?
you'd need to randomise on the plane perpendicular to the ray
hmm youre right, beacuse it works in some directions and dosnt in some others
mind explaining how?
say your ray is R, pick an arbitrary vector A, (I don't think it matters as long as it's not R)
compute a vector U = R cross A
then vector V = R cross U
you then have vectors U,V that are perpendicular to each other and R, i.e they define the plane perpendicular to R
seems like I joined in this conversation late though and may have missed some context
So i want my character (Turtle) to have an animation when you click space (so when it goes up) the video i have found recommends to use blend tree. but im not sure if i need to use float, int, bool or trigger for my animation when i press space
I usually do bool
what does bool do that the other dont/cant? or what do they all mean/do?
Hi im new to coding c sharp and im struggling with this code since when I start the game my vehicle moves to the right infinitely. Can someone assist me pls thanks
The only one that's not obvious is Trigger, which is basically a single-use boolean. Once it's used for a transition, it sets itself to false, while a boolean only changes when you specifically tell it to in code
I use bool to see if the player is in the air and when it is do the animation if Ur meant to jump
But I'm pretty new to coding
ahh okay okay just a lot to take in for the first day hahaha
if you aren't hitting any buttons, endXPos is 0, meaning your lerp will move this object towards 0 on the X axis when you're not hitting a button
If you're moving in Update, you probably don't want to lerp
Just add to the position directly when you get input
how are they both perpendicular to each other AND R at the same time?
Because 3D
Take a look at your transform gizmo, it's three perpendicular vectors

so would i somehow try implement line 6 into lines 34 and 39 while removing lerp
so like.... which... wha.... i dont understand any of this. can some one just tell me, when i have this U and V, what do i do with them to make this... work?
sorry if im being too much of an annoyance, cant help it.
they are the vectors you would perturb or sample along
a little rotation on the u axis and a little on the v axis to create a cone
fwiw, you could probably keep this more intuitive if you're not familiar with linear algebra by creating the perturbation in a simple frame of reference and then rotate the whole thing
I don't know what line 6 has to do with anything, that's just a namespace. What you'd do is add to the position when you get input, and then check if that position is outside of your bounds. If it's not, move the object to that position.
oh mb i meant line 46
can you show what the u and v axis actually look like so i could understand what im doing a little bit more? thanks
nevermind
can someone help me making a tree spawn script
but if it is above 3 what should the else statement be? Or should there even be an else statement
Just don't do anything if the move would put you out of bounds
Are you holding the E key when you enter the trigger
wdym
You're checking if the E key is currently held when you enter the trigger
oh
are you holding E while entering the trigger
how do i set fullscreen to windowed fullscreen
bc my character only moves up and down can i just use 1D blend type?
if i put a colliderStay it will work?
hello
Since you already have a boolean for being inside the trigger, check that in Update and if you are, check for key press
well i have some simple questions i would like it if anyone can talk to me in dms XD
XD
well im a beginner and i havent worked on unity in a while
does inventory and breaking and collecting system take long to make?
like breaking trees collecting wood and crafting axes
Hi ! I have an issue in my movement script. I wanted to do a air control system but when I jump and move, It looks like the player is hovering.
If I don't move while jumping, gravity is normal and it descends correctly, but if I move I glide and descend to the ground very slowly.
https://gdl.space/ipaqapunan.cs
There's my script, can someone explain me why it's so laggy, thanks !
Person A could get it done in less than a day. Person B could take a month or more on it.
Really impossible to answer
depends on what if i just focus on that would it be possible to finish it in a short while?
¯_(ツ)_/¯
any tips that might help me start in a good path
documentation and tutorial, it "works" for me
oh cool thanks
My tip is stop worrying/focusing on how long anything will take. It is not important at all at this point. It is impossible to even begin answering
Just learn Unity and make stuff
ill surely look into that
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
well yeah i know that but im not on a hurry i was wondering if i could make a good game for a project because i dont rly have anytime to waste then start on something else
XD
so if i have a chance for it i will do it but im unlucky so yk i would rather make sure i can before i start XD
Then you definitely don't have time to spend talking about starting without actually starting
AudioSources aren't affected by Time.timeScale, how can I deal with pausing an audio source when setting Time.timeScale to 0?
use an event
well, multiple audiosources
You'll have to call pause manually
as general advice, is it better to have an audio source on every gameobject that makes a SFX? Or one audio source for all of one effect?
Multiple audio sources allow you to have sound coming from multiple locations
as in for stereo?
my main concern is managing multiple audio sources to avoid 69 of the same SFX playing at one time, with slightly different phases
You can pool the audio sources so you only really have a few, but you just place them around as you play sounds
As in 3d spatial sound, which often is translated down to stereo, yes, but isn't that simple
is pooling the audio sources the smartest way?
my project of 6 months is still totally silent lol
i’m mostly asking for “what is the best sort of strategy to avoid dumb audio that is hard to manage?”
🤷♂️ you might be able to get away with just playing audio carefree. Depends on what your game is really, pooling it is just what I saw one game does
was reading stuff you don't want unused clips hanging in mem so dynamically loading
but I'd assume this is more about longer musical tracks
i’m considering pooling from a singleton, having a giant enum tied to each SFX, singleton has a pool for each value of the enum, and then classes that want sound request it from singleton using the enum as an argument
BGM would probably need to be fully loaded/unloaded dynamically
singleton does seem like the idea, but I thought each unit that wants to play the audio in a proximity must have an asset of themselves.
so you need the reference to the asset
oh yeah so singleton dictionary then
singleton can be requested to play audio at one given position, so it knows which type of SFX, and then put one of a few gameobjects at that position with the right SFX, and tells it to start playing now
assuming i’m cool with the SFX not following something, which I can live with
main question: is this smart or dumb?
so what about footsteps which each independent unit would probably want one of thier own
why the hell is “uhhh” a blocked message on this server lmao
it was a complete response with all the context needed
censorship aside, idk
so you'd probably need to pool many objects per asset if that's how it works, but again I've not really touched much on audio either
would make sense if it's just a reference call but unity
but pooling is good for one off SFX, the way I described, right?
maybe even make an SFX object prefab so it can have all the volume settings set up?
Can someone help me with this
OBS (Open Broadcaster Software) is free and open source software for video recording and live streaming. Stream to Twitch, YouTube and many other providers or record your own videos with high quality H264 / AAC encoding.
no
cant rn
if the original works and goes fine why cant its clones do the same
I really dont know how to animate it when i press space ive looked at a ton of videos but they all use transitions from idle, run to jump and stuff like that but I only have jump and i really dont know what to do 
Make a transition to your jump animation with a parameter condition, and change that parameter when you hit space
Fair. We'll be here when you can
Look at the #854851968446365696 on how to ask
It's kinda late right now and download obs could take time
Could you possibly slide this one?
I would be much grateful
I started to watch it and almost threw up. A little sick for the last few days, so it's not a willingness issue, it's a physical capability issue
The wild shaking is just way too much
i think ill just leave it for today nothing is making sense anymore idk what im doing lol
is there a better way to do this? at first i tried to nest a GetKeyUp within a GetKey thinking it was clever, then realized theres no way that would work
how to fix this guy pls help
remove line 4
ok thank
i mean, for one thing i wouldn't necessarily want to be setting x gameobject to be true every frame.. but no other ways came to mind, besides introducing a variable
x.SetActive(Input.GetKey(AnyKey));
Cursor.visible = !Input.GetKey(AnyKey);
otherwise you would need some variable to track what it is currently set to and only call the method and change the visible property when the variable changes
The code is fine already, you arent setting it every frame. If you used the new input system it might be a little cleaner but no need to worry about little stuff like this
The car moves left when the player presses A which is good but how do i prevent them from going off the map when clicking it again? I tried using an if statement on line 48 since i thought its supposed to check when the current x position is the same the minimum x position which is set to minus 3.
This seems like you're making it a lot more complicated than it needs to be. Just add a value to X when you're holding right, subtract from it when you're going left, and if the new value is outside of your range, just don't move the object's transform.position
public AttackRange CheckRangeOfAttack(){
// Example: Check if the bounds of two colliders overlap
Collider rangeCollider = shortRange.GetComponent<Collider>();
Collider otherCollider = battleManager.target.gameObject.GetComponent<Collider>();
if (rangeCollider.bounds.Intersects(otherCollider.bounds))
{
return AttackRange.Short;
}
rangeCollider = mediumRange.GetComponent<Collider>();
if (rangeCollider.bounds.Intersects(otherCollider.bounds))
{
return AttackRange.Medium;
}
rangeCollider = longRange.GetComponent<Collider>();
if (rangeCollider.bounds.Intersects(otherCollider.bounds))
{
return AttackRange.Long;
}
return null;
}
Hey guys, having a function that returns a value based on certain critiria here, however it returns a value of a enum. Which means null cant be send back yet something has to be send back when all the other if statements fails (even though that should be happening ofcourse). What is the good practice in this scenario?
Pick one or make a new Enum option for "none"
why is my flipStrength default value is different than what it is on unity,whileas my moveSpeed default value is the same than what it is on unity
it's been serialized to another value
Because you've changed one of them
the value you've set in the script is the default value if you were to reset it
ohh right, i thought value what's on script and what's on unity will synchroniniize with each other lol. how do i reset the value on unity so then it'll follow the default value on script then?
Reset the script
uhh sorry how
Right click, reset
true, im making a top down point click prototype.. and the selection system is going to end up being a bit complex,
- being a single click and release both starting and stopping on the target counts as 1 interaction
- a click and release can either do 1 interaction in one scenario or another interaction in another
- a click and drag (clicking on an object and releasing while off of said target) is another interaction
- lastly a click and hold (doing different things according to which scenario
soo.. the new input system may be a real solid fit
works, thank
do yk if there exists any free or cheap extensions for building like raft rust the forest...
i dotn knwo how to get my character to basically have a mesh model and the limbs to actually animate to the actual character
hence carrying over movement from bean to a actual player model
Learn the fundamentals of animations in Unity3D! From the basics of moving a cube to customizing a character animation!
This beginner-friendly tutorial is a thorough break down of Animations in Unity 3D! You will learn how to use to use the animation tab, how to record and modify animations, what animation curves are and how to use them and how...
Wait, actually, that's like halfway through the series, here's the full playlist:
https://www.youtube.com/playlist?list=PLwyUzJb_FNeTQwyGujWRLqnfKpV-cj-eO
look into the unity rigging package too, later on.. to combine different animations
you can have the torso doing one thing, and the bottom animating different, generic animations
animation rigging*
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
how do i assign my blog
what
📃 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.
the playlist is rly gd thanks for sharing although im not the one that asked for it
they do synchronize, but the benefit here is you can change the value for this instance through the editor because changing the value in the script would otherwise change all other instances (assuming you didn't change those instances specifically)
you
you're right 😮 i could just mess with the value through editor to test out stuff instead of in script since yk itll cause more effort and yeah
I'm receiving the error in red. When I launch the game and click anywhere to move it throws that. I don't understand because if I were to create a new project the code works fine.
Do you have a camera tagged MainCamera
AHHHH
You were right.
I completely forgot to change it back
Thank you digholic!!!!
btw you don't have to check that the hit.collider is not null here, doing that just indicates whether the raycast actually hit anything. but Physics.Raycast returns true if it hit something so it's kind of a pointless check
Oh? I'll review that. Currently following this tutorial: https://www.youtube.com/watch?v=zZDiC0aOXDY&ab_channel=samyam
In this video I'll show you how to use the new Input System to move your player to where your mouse has clicked in 3d space.
ᐅGet the full Source Code Bundle to my Unity Tutorials 🤓
https://sam-yam.itch.io/samyam-full-source-code-to-all-videos
📥 Get the Source Code 📥
https://www.patreon.com/posts/60737375
🤝 Support Me 🤝
Patreon: https://www....
why is overlapnonalloc more efficient?
it doesn't need to allocate a new array every single time you call it. it just populates the array you pass to it
allocating objects (such as an array) and cleaning them up (aka garbage collection) takes some time. By reusing the same array you skip doing this, paying only an up-front cost to allocate an array which you reuse
what if the amount of objects in the overlaycube exceeds the array length?
have you bothered reading the documentation for the method?
naw
Friggin docs are out for our jobs!!
They’re op I have them open in a tab constantly lol
how can i draw a cube gizmo with a rotation? the docs only show position and center
im trying to debug an overlap box but i cant see what its scanning cus im using a rotation
soo rn im trying to get a perfect bounce using a 2d physic material but i cant get the object to go to the same place it dropped it seems to go higher
where is the code question?
my bad wrong channel
yeah that is more a #⚛️┃physics question
thanks
You set the transformation matrix of Gizmos with Gizmos.matrix. You can pass a transform.localToWorld matrix and then all subsequent gizmos will be relative to that matrix. Or if you only want rotation, you can create a rotation matrix with Matrix4x4.Rotate
I am making a chess program and have OnMouseDown, OnMouseDrag, and OnMouseUp logic attached to a controller script on every prefabricated piece. I haven't been following any guides, so right now I'm just doing things that work, but I have a gut feeling that this isn't good practice. Anyone have any suggestions, or is this alright? https://gdl.space/butoquhepi.cs
#💻┃unity-talk message does anyone know wtf is going on here
#💻┃unity-talk message added info
How would I be able to get the direction of which my transform needs to turn in order to look at another object/position? I.e. turn right or left.
use transform.left/transform.right
how would I make it find out which side to turn?
also Vector3.RotateTowards works better for this kind of thing
right but I need to find out which direction in order to determine which animation to play
theres turn right and turn left
I'm unfamiliar with that type of movement control, but I feel like adding a default condition where x and y == 0 might help
I have an angle calculation formula but it only gives a float based on how far they are from the front
you can probably figure it out from rotatetowards
just work out last rotation vs newest
reading directly from euler angles is a bad idea as they're reinterpreted from the internal Quaternion value; cache your own euler values and apply them
ok ill try
Oh I misread your comment, I thought it said when there was no camera movement, not 'also when there is no camera movement'
Also obligatory: use cinemachine
i have no clue what this means or what you want me to do here (i am very stupid)
Keep track of your own set of angles which you use to update the transform instead of reading from .eulerAngles
says in the unity talk that doesnt work
oh wait wrong one
can't find the video but there's a little snippet about disabling
feeling like the video is hidden cause I cant find it now haha
https://www.youtube.com/watch?v=_wxitgdx-UI&t=1410s
Ah, ok it was in that video
Mark and Ian from Unity's Enterprise Support team run through performance best practices drawn from real-world problems. Learn the underlying architecture of Unity's core systems to better understand how to push Unity to its absolute limits.
For more information on Unite Europe and future Unite events visit this page. https://unite.unity.com/
...
25 minute mark
Relative to what in particular?
What I mean is that usually it'd be relative to position, assortment or some other type of data
like all of them as possible
Whats the difference between Vector3.MoveTowards vs Quaternion.LookRotation? The result is the same right?
it really depends tho
i would say quite a lot of the UI has no relation or to certain position
The result of one is a Vector3 and the other is a Quaternion
They're absolutely unrelated?
no?
https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
Calculate a position between the points specified by current and target, moving no farther than the distance specified by maxDistanceDelta.
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
Creates a rotation with the specified forward and upwards directions.
What's similar?
What i meant was that the use case seems similar, to rotate an object towards a position
MoveTowards doesn't rotate things towards a position
quarternion controls ur looking(rotation mainly), like when u walk over the street, you looked at a restaurant, thats lookrotation
movetowards feels like someone pushing you right into the restaurant
One creates a point between two points and the other creates a rotation from two direction.
ahhh sorry Vector.RotateTowards is what I meant
I'm not sure where the confusion is.
LookRotation constructs a rotation, RotateTowards moves a direction
it seems like both Vector3.RotateTowards and Quaternion.LookRotation use cases are the same
How so?
Now the only relation is that they both relate vaguely to directions and rotations. There's really no similarity
Same as before. RotateTowards returns a Vector and LookRotation returns a Quaternion
The docs for RotateTowards USES LookRotation to set the transforms rotation...
https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
You'd use rotate towards if you're wanting the next stepping towards a certain value. You'd use look rotation if you're wanting the value relative to another factor.
If what was wanted was miniscule, they may look to operate the same but they're quite different.
So Vector3.RotateTowards is like getting the direction needed to get there?
They both give you directions. The first with a maximum delta. The second relative to a second direction.
Different tools.
Quaternion.LookRotation gives you a rotation from direction(s)
RotateTowards rotates a direction towards another one
they are not related
what would be a use case for the Quaternion.LookRotation over RotateTowards and vice versa?
Why
The Rotate Towards doc made use of both #💻┃code-beginner message
They're used for different purposes.
It's not one over the other - they aren't subsets of each other (do not overlap)
Neither can be used in place of the other
You're essentially asking why use AddForce instead of setting the mass
There is a thread of a connection, but they can't be used to do the same things at all
The first one is when you want to transform a direction vector to a quaternion. The second one is when you want to rotate between 2 quaternions
ah ok i see so you need both
{
TurnDirection turnDirection;
Vector3 delta = (_target.position - transform.position).normalized;
Vector3 cross = Vector3.Cross(delta, transform.forward);
Debug.Log(cross);
if (cross == Vector3.zero)
{
turnDirection = TurnDirection.Back180;
// Target is straight ahead
}
else if (cross.y > 0)
{
turnDirection = TurnDirection.Right90;
// Target is to the right
}
else
{
turnDirection = TurnDirection.Left90;
// Target is to the left
}
Debug.Log(turnDirection);
}```
Im getting a return value that the target(cube) is to the right of the zombie here which doesn't make sense. The value is (0,1,0) even though the cube is clearly to the left.
thats tuff
You considered turning it on and off again?
yea i tried that haha
shi idk then, I usually just punch my screen
that fixes my anger issues at least.
yeah i don't think cross product would be the correct operation to use here
This is overcomplicated
Just use Vector3 localPos = transform.InverseTransformPoint(_target.position);
that local position will tell you everything you need to know with the sign of its x component
alright ill try it out thanks
Negative is left, positive is right
Likewise for the z coordinate for front and back
yea this is much better thank you
hi i have a problem
when i import a model
and is that the bones appear to be missing in animator editor
this is a code channel
Random how ? This code will move the object in the world up direction
use id:browse to find a channel relevant to your question
Then again using Translate like this probably will not result in the desired jump behaviour
What does this do? I'm confused because nothing has been assigned to it yet. and im not familiar with this syntax (=>)
I thought maybe its been assigned in Unity editor but no option comes up to insert a 'SceneName'
oh. yeah I am following a tutorial so this is not my code.
It's basically same as saying return m_sceneActive. It's a property.
Same as a method that returns the value on the right side.
So like this?
public SceneName SceneActive
{
get { return m_sceneActive; }
}
Yeah, that's a different way to write a property.
Thank you.
I did not know about this documentation guide. Will definitely bookmark this. 👍
What about this one. Looks like they subsribe to 'onLoadComplete' event that is called when a scene is loaded.
I'm looking at the function and was wondering how they get the values for the parameters since no arguments are being passed in. the function is just "called" from what I can see.
the OnLoadComplete event is a delegate that requires those parameters
https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.8/api/Unity.Netcode.NetworkSceneManager.OnLoadCompleteDelegateHandler.html
Well I would suggest to find a tutorial that at least uses a character controller. Simply translating like this will ignore physics collisions and lead to a whole mess of other problems
📃 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.
hey so im trying to use animator for my doors, and im getting this what am i doing wrong?
Is it DoorOpen or doorOpen? Because you made a string with capitals, and then put a string without it in play.
that just changes the string to "DoorOpen" or "DoorClose"
thats so if i want multiple doors not sure if i need that for multiple doors though, jsut adapting some code from a tutorial, and the error still happens with or without the private strings
What is your animation state called? Its saying it can't find the not capitalized ones as far as I understand.
If the state is the DoorOpen you should play that.
Sure, but it's capitalized here... Which was my whole point. What if you actually play the correct name?
huh i see
You are aware you are not using the private strings you defined at the top right?
yeah i realized that after
will i even need those to have multiple instances? or will they all open and close seperately without it?
I don't understand what you mean with multiple instances.
Currently you are telling your Animator myDoor component to play OpenDoor. So only that Animator will open his door.
i jsut mean having multiple objects with this script
when i interact with one of them will all of them open or just hte one im interacting with
Currently you are telling your Animator myDoor component to play OpenDoor. So only that Animator will open his door.
ah makes sense
i completeley understand.
yeah works like a charm thanks
would you happen to know why my door is only closing? im like super unsure, thought this would work
the initate works but once it opens and i close it after the close frame it just goes back to the last frame of open
your logic is flawed. Look at your code and what happens if Close is true
oh goddamnit i see it now, huh i looked at it like 4 times LOL thanks!
you dont need both Open and Close, just use one of them
alright
Ya you don’t need 2 booleans to track the same state.
If a door isn’t opened then it’s obviously closed.
Unless it’s a 4 dimensional door 🤔
rip random method
there's a secret tidbit in there
a simple trick, you can hover on the method to see what overloads you are calling
why does float get the privilege of being max inclusive
Apparently I need to specify UnityEngine.Random? But the example didn't, and I used to just write Random.Range
if you have the System using directive that is going to happen, just like the docs page says
Define doesn't work, because it would be a compiler error if you had it that way
As in it sent me a compiler error
Please specify next time so people don't presume your issue is something else
I'm aware of that, I just don't understand why Random.Range worked before and now it needs to be UnityEngine.Random.Range
because you used some System method and it injected itself into your script
https://docs.unity3d.com/ScriptReference/Random.html
read the docs
Without the compiler error I don't think anyone should help
'Random' is an ambiguous reference between 'Unity.Mathematics.Random' and 'UnityEngine.Random'
Great, there you go. You are using the mathematics library, and so it's ambiguous what random you are talking about when you try to use it
otherwise you can do like an alias was it called?
Did Unity update this? Because I don't remember needing to specify a couple of months back
I didn't add the library though
You added the using.
If you use a method from the library without using then it'll do it automatically
but if you are using the math library too you can do something like this I believe
using UnityMathsRandom = Unity.Mathematics.Random;
using UnityRandom = UnityEngine.Random;
Or to whatever you prefer to remove any ambiguity
My site mentions both of those things 👍
oh specific to the random library too haha
is it ok to overuse C# actions and funcs ?
define "overuse"?
I have my items as Scriptable Objects in my game client.
But to prevent cheating (multiplayer) I need them to be server side.
I want to manage the items in the unity editor though, what's a good way to make sure my server always has the correct & latest version of the items?
Knowing we cannot trust information sent from the clients.
Would it be possible to keep the "main source" in a spreadsheet and change values there
then import that spreadsheet to both my database and Scriptable Objects?
seems like research
Just don't include the files in the client build and include in the server build.🤷♂️
It shouldn't be too difficult if your server is built with unity.
server is not unity 😛
well it's on unity game services
but looks like the spreadsheet thing should work
do you guys know how do I detect if my characterController is colliding with another box collider?
That shows rigidbody
if you are trying to detect collision between colliders, one of them must have a rigidbody or try Physics raycast overlap functions
raycast is useful but I can't see the distance properly as it stays invisible
try using gizmos to draw the radius/other info
that way boundaries that you want to see will appear in scene view
for PlayerInput, many things in game might want to reference that one component, so it’s better to not have it really tied to any one thing that really uses it
yes
still yes
Does anyone know how to fix camera moving by itself? I have used a free first person controller asset by the unity store, and for some reason the character keeps moving in front with a little bit of left.
i had that issue by another code that i tried in another unity project, where the camera just floats in the sky.
might be an issue from my unity but yeah help
like if you later decide to have multiple character objects, and swapping the character or enabling/disabling it, then you can run into trouble because your playerinput is on it
https://paste.ofcode.org/wfqBmihKe2mc643dx5cL66 im trying to add knockback to my players attack so i thought i would implement it where my enemy takes damage but i am getting a null reference exception error when hitting my enemy and i dont know why
have you debugged it and made sure you're grabbing the collider of an enemy
i dont know how i would debug if im getting a null reference exeption the second i hit an enemy
show code at 60
here
right, along with the Trigger method
oh, so the rb is on the script itself, but not what you're colliding with eh
rather what you're applying force to.
the rb is on the enemy im applying force to yhough
but your rb isn't instantiated, so make sure the component is set in start or in the editor there
half asleep, but if that's the line, then yeah go log that rb is set
ah right
if you're meaning to grab the rb from the collision target, then you need to GetComponent from that instead
inside of the trigger method
i got it working thanks
ah kk
i forgot to do GetComponent in start
the knockback isnt working now though
im just not getting a null reference exception
Ye, uncheck those for sure. It won't move in any direction with all those marked.
how would i make it so it still floats
because my enemy isnt walking on ground
how can I make my object move in another objects z axis?
Like I'm making a simple wall run and when my detector object touches the wall I want my player to move forward in the walls z axis.
I’m assuming that it’s sinking into the ground a bit? Edit the collider and make it taller
thanks
How are you moving the object?
Just noticed this image, does it need to be a trigger collider?
yes for the enemy health script but its fine
Using a movement script?
I mean using key input
No, I meant how are you coding it to move. Like is it a rigidbody? or transform?
character controller
im curious, can you retreive the "tag" of a gameobject from a collider by doing collider.tag
i cant go check in unity so i am askign here
im pretty sure you can't
https://docs.unity3d.com/ScriptReference/Collider.html Collider > inherited members properties
You can get the z axis of your wall by finding the cross between the wall’s normal, and the world’s up position. Raycast on either side of the player, and then run Vector3.Cross(hit.normal, transform.up)
so I wanted to do a build test and I am getting some "this namespace couldnt be found"
but when I check by opening the line in VS, i get no errors
example:
what can cause this issue when building ?
but how do I write/tell the player to follow the cross of the wall?
I'm using a rigidbody detector
If it's true then I want it to follow the walls cross
I doing like this
The UnityEditor namespace isn't available outside the editor
ah yes i forgot
ty
the thing is, how I prevent from trying to compile ?
I am using this lib in some of my scripts, it helps me for the inspector and for serializing stuff, so i need a part of it for the build
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, playerLookRange))
{
if (hit.transform.CompareTag("NPC"))
{
pressEToDoThing.SetActive(true);
}
else
{
pressEToDoThing.SetActive(false);
}
}
im trying to show a ui whenever i look at an npc it works but when i look at the sky (or something which is not a game object) the ui stays on
ohhh ok
Yeah because your code does nothing when the Raycast hits nothing
thanks
if (Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, playerLookRange))
pressEToDoThing.SetActive(hit.transform.CompareTag("NPC"));
else
pressEToDoThing.SetActive(false);```
yeah thanks i figured that out
thank you everyone
https://docs.unity3d.com/ScriptReference/Vector3.Cross.html It returns a Vector3 that will tell you the axis to move the player on. I believe that you move in the negative direction of the axis if the wall is on the right side. Similar to how you are using input to tell the direction the character controller moves, use the axis returned to figure out the direction to move the player
is OnTrigger[...] called on the GO where the collider is set to trigger or on both colliders
I want to move the number one, but I cant, can someone help me out
read the docs?
its nor written
or at least not precised well enough because I wouldn't be here
The collider with the istrigger calls the callback function
ok ty
what do you need?
you want to move it with code or just move it within editor
it is
At least one of the two colliding objects needs to be a trigger, but BOTH receive the OnTrigger message
I don't know why but when commiting Changes on Visual Studio Code it is loading with no progress...
Hello! Can anybody explain me how can I make the rotation more smooth? I think I can use the Quartenion.Slerp but im struggling with the start and end points (what to put in there)
This is how I rotate the kart:
void RaycastGroundCheck(){
RaycastHit hit;
isGrounded = Physics.Raycast(transform.position, -transform.up, out hit, 1, groundLayer);
transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
}
(Its in Update)
the quick and dirty way to do it is just:
void RaycastGroundCheck()
{
RaycastHit hit;
isGrounded = Physics.Raycast(transform.position, -transform.up, out hit, 1, groundLayer);
var targetRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation , Time.deltaTime * 10); // or some other magic number
}
the problem here is just that slerp (or lerp) is not really intended to be used like that, but it does work
It no work
Why is it "dirty" tho?
it's a matter of preference I suppose. but for me the problems are that slerp here won't follow it's graphed value because the target and interpolation factor constantly change (but it will be smooth) and that tickles my tism the wrong way 😄 as for the dirty part we're not tracking target rotation and rotation(model) smoothing as two different concepts, we're just doing it all in the same go.
as for why it's not working, that's a bit of a mystery to me, are you calling RaycastGroundCheck every frame? maybe try a different number than 10 here? Time.deltaTime * 10
so maybe something more like this
public class GroundAlignmentScriptThingy : MonoBehaviour {
public LayerMask groundLayer;
public float smoothingSpeed = 10f;
private Quaternion targetRotation;
private bool isGrounded;
void Update()
{
RaycastGroundCheck(); // calculate the 'real' rotation
SmoothRotation(); // update the visuals
}
void RaycastGroundCheck() {
isGrounded = Physics.Raycast(transform.position, -transform.up, out var hit, 1, groundLayer);
if (isGrounded) {
targetRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation; //align with ground
} else {
targetRotation = Quaternion.identity; // if we're not on the ground, maybe just point upright? I don't know
}
}
void SmoothRotation() {
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * smoothingSpeed);
}
}
you can have a varible that u slerp to.. u can control the smoothness of the slerp and just change the variable to the rotation u want
should be able to smooth it out some
but yea, guys correct about the slerp being incorrect
or just use DOTween and save yourself all the issues with quaternions
u shouldnt pass in the variable ur actually rotating as that first parameter
u need to cache the starting position first and use that instead.. so ur lerp isnt using itself to calculat
i have this same setup. and yea the key is to:
- fix the slerp and make it proper
- use good models for ur ramps and stuff.. the more faces it has the more smoother ur rotation will be..
Hello devs, who knows? code simplified .
u can wrap the bottom else stuff into a function..
call that function from the top else and the bottom else
||I've unironically used goto in cases like this||
will Break or return help here?
that looks like a pretty bad architecture, i imagine it is unpleasant to work with
imagine you want to add a new feature into the already nested if/else statements
but I'm not joking, nested elseif chains are the only place where 'goto' can be used.
Seems to me like you should start with the > 90, use an else if for > 70, and then an else if you still need it
more like, if you are using goto, then probably your architecture is wrong
but it could be broken into specific pieces if u want
so no break or return can help here ? code itself very cumbersome so even i cant find begining and end
ngl that code is kinda hard to read with that bracket formatting
sure that's the tale / rule you tell new developers, but experience let's you break the rules 😉
that formatting really is off-putting
sure if your experience tells you to use goto, and chains of nested ifs then go for it xd
ok thx. will try something
There is no loop to break out of and return ends the function. Please read what I wrote above your logic is a mess and you should reorganize your checks
Formalize your rules for what you want to happen and when
And then you can simplify
Start by identifying which outcomes you want. List them all out, and then what conditions have to be true for that specific outcome to occur
Once you do, you should see some repeated and shared conditions, which will inform the order and structure of your conditionals
afai can tell, this is the problem you have:
void ExampleMethod()
{
if (condition1)
{
// Some code
if (condition2)
{
// Some code
goto End;
}
else
{
// Some code
}
}
else
{
// Some code
}
End:
// Code to execute after the goto statement
}
now given that, if you don't want to use goto, the only solution is to nest methods so you can use return. or rewrite the logic without the nested problem, or duplicate code.
void ExampleMethod()
{
if (condition1)
{
HandleCondition1();
}
else
{
// Some code for else part
}
// Code to execute after the conditions
}
void HandleCondition1()
{
if (condition2)
{
// Some code for condition2
return;
}
// Some code for else part of condition2
}
don't use goto please
i use the same slerp method as you
Quaternion toRotateTo = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, toRotateTo, alignToGroundTime * Time.deltaTime);``` and also wrong too btw, but with a decent 'alignToGroundTime' (i use 20 in this case) it seems to be pretty smooth
just refactor your architecture, it is wrong
The real solution:
if (condition2) {
// some code
} else if (condition1) {
// some code
} else {
// some code
}
// some code
if someone is experienced, he doesn't do chains of nested ifs, therefore he doesn't need to use goto (which is very bad practic to use), or when he does that kinda means that his skill didin't follow his experience 😄
In a modern C# program, without the bounds of needing to fit a program into a register or dealing with the file size of a punch card, you will never use gotos. All goto situations can be made easier to write, cleaner, and notably easier to maintain by just properly formalizing your rules beforehand and a few function calls
what's the reason why unity cent display props in the editor by default again?
I have never used goto in my entire unity journey
same other than making memes
[field: SerializeField] public float MyProp { get; set; }
Because a property isn't a variable, it's a pair of functions. If you're using an auto-property, there is a variable, but it's hidden. The default state of a variable is private and non-serialized. Since you can't actually put a public or a [SerializeField] on something that doesn't exist in your code, Unity provides a way to access that anonymous inner field with [field: SerializeField] on an auto-property.
how do i make it know that i mean if the player collides with the ground? i added the public game object and draggen the player there
learn how references work, this is nonsense
I have extensively used goto in Fortran, Assembly, and ARM. You will never use it in a modern object-oriented language
uh oh..
facts 
The abstract concept of Collisions does not have a gameObject
unless you are experienced, then you can break the rules kappa
is it unavoidable in those early languages?
never worked with assembly, but i can imagine it would be kinda impossible to work with it without goto
It's not unavoidable, but when you're coding for a microprocessor with like 600 bytes of ROM you need the space
branch statements are a lot bigger than gotos
Basic is the same
goto is a must
You should learn some basic unity tutorials first, and then watch a guide on how to detect if a object is grounded or collides with other object or whatever you need
what if we have a /huhhow collision that auto links to vertx's specific page
No, you didn't. No tutorial would write that.
The one difference being that theirs probably properly used an OnCollision function and used a parameter instead of trying to access the class directly inside of Update
okay so upon rechecking the code they did not put in in update i see the probkem now
yes i just noticed that lol
oopsie
yea, they put it within the collsion detection
How do I access data from a scriptable object
make a reference to it?
same way you access everything else
ArgumentException: GetComponent requires that the requested component 'NPC' derives from MonoBehaviour or Component or is an interface.
whoops
meant to send this
this is the error it throws tho
you dont need getcomponent
Is NPC a component?
You have to access whatever holds the SO
GetComponent gets components (shocking, I know)
i feel stupid now 😭
You'll want to get whatever component holds the NPC value
alr
if i understood it correctly, this returns a value based on what direction the player is moving, if its right, its 1, if its left, its -1 and up and down are 0?
that doesnt seem right lol
is the ramp on the ground layer.. or w/e layer ur raycasting down towards to get the normal?
Yep, the ramp is Ground layer
looks like the cars trying to stay str8 (like the plane) even when its going up the ramp
is ur raycast hitting it?
debug the raycast that gets the normal and see if its the ramp
or if its hitting the car's own collider or something
heres the project i was using.. its all set up. could maybe use it to reference and compare..
I completely forgot how I rotate the kart to align it with the sphere
I confused the axis that should freely rotate and I changed it and now it works.
This is how I rotate it (works now)
transform.rotation = new Quaternion(transform.rotation.x, _rigidbody.transform.rotation.y, _rigidbody.transform.rotation.z, _rigidbody.transform.rotation.w);
I made so the the kart rotation equals rigidbody rotation but except the X axis (its the forward/backward rotation axis), now it works
Thanks!
i am working on playerMovement animations
and i want to implement sliding but when i press c while running nothing happens
{
if (Input.GetKeyDown(KeyCode.C))
{
rn_speed += sl_speed;
playerAnim.SetTrigger("Sliding");
playerAnim.ResetTrigger("Running");
}
if (Input.GetKeyUp(KeyCode.C))
{
rn_speed -= sl_speed;
playerAnim.ResetTrigger("Sliding");
playerAnim.SetTrigger("Running");
}
}```
start debugging then
What function is this in
this is the function that says when i am running i want to slide when pressed C
In that case your issue is the syntax error because this code is not inside a function
yes its just a part of the code
So what function is this in
update function
Okay good. And when is Running set to true
actually maybe just post the full !code so I don't have to play 20 questions
📃 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.
okay wait
{
if(Input.GetKeyDown(KeyCode.W))
{
playerAnim.SetTrigger("Walking");
playerAnim.ResetTrigger("Idle");
walking = true;
}
if(Input.GetKeyUp(KeyCode.W))
{
playerAnim.ResetTrigger("Walking");
playerAnim.SetTrigger("Idle");
walking = false;
}
if(Input.GetKeyDown(KeyCode.S))
{
playerAnim.SetTrigger("BackwardsWalk");
playerAnim.ResetTrigger("Idle");
}
if(Input.GetKey(KeyCode.A))
{
playerTrans.Rotate(0, -ro_speed * Time.fixedDeltaTime, 0);
}
if(Input.GetKey(KeyCode.D))
{
playerTrans.Rotate(0, ro_speed * Time.fixedDeltaTime, 0);
}
if(walking == true)
{
if(Input.GetKeyDown(KeyCode.LeftShift))
{
w_speed = w_speed + rn_speed;
playerAnim.SetTrigger("Running");
playerAnim.ResetTrigger("Walking");
}
if(Input.GetKeyUp(KeyCode.LeftShift))
{
w_speed = olw_speed;
playerAnim.ResetTrigger("Running");
playerAnim.SetTrigger("Walking");
}
}
if (running == true)
{
if (Input.GetKeyDown(KeyCode.C))
{
rn_speed += sl_speed;
playerAnim.SetTrigger("Sliding");
playerAnim.ResetTrigger("Running");
}
if (Input.GetKeyUp(KeyCode.C))
{
rn_speed -= sl_speed;
playerAnim.ResetTrigger("Sliding");
playerAnim.SetTrigger("Running");
}
}```
lord..
the full !code, posted properly according to the bot
📃 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.
i have put it in the bot but how can i export to here?
paste the link
thank you
literally nothing ever changes running
it's never true
what do you mean?
I mean literally nothing ever changes running. It's never true.
its true when i am walking and then press left shift?
Where do you set it
no problem, i knew it was something weird going on
Yeahhh now i see it its fixed Thanks a lot
Why is the table not getting highlighted? probably something to do with collision idk but heres the code, maybe the gizmo and overlap box are not the same?
code attached here
Hey guys, how can I change a toggle's value without triggering its event?
nice, thanks
when i am standing in idle mod or not moving my player glides over the floor anyone knows why this happens
just guess but it does look like collision problems.. remove all the cubes but that (1) and see if it highlights
i moved the box by itself off recording and it works so