#💻┃code-beginner
1 messages · Page 495 of 1
Big Unity L
yeah
But thanks :)
Brain fart moment. I've got a raycast going from the camera. Is it possible for it to trigger a method just once when it hits the thing I'm looking for, and also, to trigger another method just once, when there is no 'hit' ? 😕
Sure, everything is possible
it will only do things once unless you write a loop
or if you run the code multiple times
for example if you put something in Update, that happens every frame
Sorry, I should have mentioned that it's in my Update() cause it needs to be constantly 'looking' 😕
Ok then you just need to track what you're looking at
and only do the thing you want when you first start looking at something new
it all depends how you want this thing to behave
Anyone know why VisualStudio keeps spamming me that TextMeshProUGUI could not be found? Also namespace name UI does not exist in the namespace UnityEngine? My game still works, so no compiler errors, but I'm afraid to save and push to github if this is gonna bite me later. Only thing I know I've done is switching between windows build and web build. Prior to that there were no errors in the scripts.
You need to configure your ide properly. See bot message below
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
• :question: Other/None
try regen project files
TMPPro is available in the hierarchy if I want to create a new gameobject
Sounds like your IDE connection to Unity isn't working properl;y
Hi I'm still having problems with this script, I refuses to disable, and now It won't ENable so I don't know what to do, I just started doing code again, so don't judge me https://hastebin.com/share/cegekoluwa.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it refuses to disable and now it wont enable? explain
Installed through unity hub and there no update or anything in package manager, just remove.
How to do that?
Okay, quick and dirty explanation, I'm using Feel from MoreMountains a lot in my current project. The thing I'm trying to do at the moment is......
When the raycast hits a certain type of object, it triggers a Feel controller that simply increases the Weight of an IK rig attached to the players arm from 0-1, 'raising' the arm so that it points at the raycast 'hit'. This funcionality I have working great, I have the arm raising up etc. The issue I'm having is the opposite action (Arm lowering/weight animating back to 0). The Feel Controller is all correct etc. It's my if(raycast....blah blah} else {lowerarmstuff] that's bugging me. lol.
void Update()
{
RaycastHit hit;
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, maxRaycastDistance, interactableLayerMask))
{
if (hit.transform.gameObject.CompareTag("Ore"))
{
Debug.Log("Arm Should Deploy Here");
shoulderObject.LookAt(hit.point);
if (!armRaised)
{
Invoke("ArmRaise", 0f);
}
}
}
else
{
Invoke("ArmLower", 0);
}
}
Sorry if it's too long, but that's what I have so far (I thought Invoke would be the solution, but after looking at it and thinking about it, I realised I'm an idiot. lol.)
Probably, but I dont know how to fix that
close VS there should be a button inside External Tools in Preferences in unity, click it then open script from unity again
It is a button script, when pressed it (is supposed to) calls Enable() but now it doesn't and I dont know why
so the log isn't called/printed ?
Thanks. Any risks in regenerating project files?
nope
No it is, but then disable happens RIGHT after it is enabled
So if I remove it, then it gets enabled but won't disable
so is the log inside Disable called ?
check the stacktrace and see who's calling it
Doesn't seem to have helped. Then again nothing seems to happen when I click regen project files. The button gets clicked but nothing happens
yes, RIGHT after Enabled() is called
I would go back through the IDE configuration guide
What does ArmLower look like?
can you also show the Solution Explorer view in VS real quick
curious to see whats happening there
void ArmRaise()
{
//weaponArmIKRig.weight = 1;
raiseArmPlayer.PlayFeedbacks();
armRaised = true;
}
void ArmLower()
{
lowerArmPlayer.PlayFeedbacks();
armRaised = false;
}
oh thats weird
Unless I missed something the guide only talks about configuring, intalling, and updating. That doesnt seem to be the issue
Should you not have a similar cs if (armRaised) Invoke("ArmLower"); check there?
I wonder if its only loading the main assembly and not the external package ones.. def try going through the steps again for VS config.
if you expand References under Assemblies, I wonder if you find the UI one there (prob not)
Also why are you invoking it instead of just calling it
I was just trying something tbh before I realised I was being stupid. lol.
Not entirely sure whats happening here but maybe you wanna call ArmLower also when the raycast hits something but it's not an Ore?
yeah that's an excellent point^ you're missing a whole branch of the logic tree
I think the cleanest formulation here would be like:
bool hitOre = false;
if (Raycast(...)) {
if (hit.COmpareTag("Ore")) hitOre = true;
}
if (hitOre && !armRaised) ArmRaise();
else if (!hitOre && armRaised) ArmLower();```
(pseudocode to show the logical structure)
Okay, I got it working. (probably terrible implementation, but for the moment it works, so I'm happy. lol.)
RaycastHit hit;
if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, maxRaycastDistance, interactableLayerMask))
{
if (hit.transform.gameObject.CompareTag("Ore"))
{
Debug.Log("Arm Should Deploy Here");
shoulderObject.LookAt(hit.point);
if (!armRaised)
{
ArmRaise();
}
}
else
{
if (armRaised)
{
ArmLower();
}
}
}
don't you need to also handle the case of not hitting anything?
With all the things I'd tried, one small detail I missed. I forgot to add the 'terrain' layerMask.
And I don't think so. If it's not looking at 'ore' specfically the ik rig is set to 0 and the player is completely goverened by animations.
Bunch of UI stuff but I guess not the one I need?
Does it ever happen that VS configs get scewed up when switching builds?
I've always been in the windows build and never had this issue before, then I switched to web and got the errors, switched back to windows and it's there now too. The game works though, no error messages in Unity, it's only VS that give me this.
yeah you see the ones missing have exclamation mark for some reason VS is not detecting them
the ones in UnityEditor work fine for some reason
A bit of context if anyone is interested. 🙂
In the future it's probably going to be better if instead of checking for a tag like "Ore", you put a component on these things like "Interactable"
then you can detect any interactable thing including things that are not ores
Yeah, that's the whole idea, I just wanted to get this part working. The ores will be sriptable objects etc.
All my current interactables are using that method. 🙂
Sorry to ask again but do you have any solution regarding to my problem about jumping less when i jump on the edge of a platform? @wintry quarry
Current State of what I have 🙂
Neat
Honestly, that Interactable script you shared a while ago is suuuuuuuch a time saver. lol.
Where is your original question?
Did you provide code in the question?
@steep rose here and we discussed a bit about it
Yeah well
!docs
Okaaay.. and what is this?
It's not supposed to snap to world 0 when i do that, might have something to do with it converting localPosition to world Position? but i'm not sure
The idea is, it should slide along it's up axis but where it's already at
This would be the desired result
The problem is that, well, this one isn't locked to a single axis
This is the script, the only difference between those two videos is that at like 54 in the script, first video is ' transform.position = Vector3.Project(hitPoint, transform.up);'
before the position is set, project it from the position it's at.
second is transform.position = hitPoint;
yeah they do project it.
You can take the code as it is (probably) and in the end make sure that the position is Vector3.Project(whatever you're grabbing, The axis is must follow)
oh, nevermind
I see your issu enow
issue now*
you want it to follow a plane yes @nocturne kayak ?
There's a function called Vector3.ProjectOnPlane. In your case, you'd use transform.up to define the normal of this plane. Vector3.Project projects only onto a single axis, not a plane.
that should achieve the desired result.
Oh, i want it to be projected on a single axis
oh.
I didn't use projectonPlane, but it is already snapping to a virtual plane i created
so what's the issue exactly?
aha, I see what's happening now
the projecting works in world space. You must add the cube's position transform.position when you set the final position of the object.
I'm assuming it's following world zero.
Vector3.Project should be used with a direction vector, not a position. I thought someone pointed this out to you at some point
// Direction from target object to hit point
Vector3 dir = hit.point - targetObject.position;
// Project that direction so that it "snaps" to the axis
Vector3 projectedDir = Vector3.Project(dir, transform.up);
// Add the projected vector to the target object's position to get the final world space position
Vector3 newPos = targetObject.position + projectedDir;```
Uhh something like that?
Could be completely off, I need some ☕
Someone did, there was something about converting it to worldspace and back to local, but it was 1 and something AM and i was crashing
It's important to understand the difference of a position vector and a direction vector
Anyway, try the snippet I provided
Can someone help me with my lights dont work? When I drag in lights they dont give off any light
what kind of light are you trying to use?
What objects are you expecting it to illuminate and how are they rendered?
oh i didnt know that, ty
@nocturne kayak Btw just fixed a major typo in the snippet, was using hit.point inside Project instead of dir. Edited
would you take a look at it in the other channel?
Post your question in lighting channel and we can take a look. Also provide the info that Praetor was asking
someone free to dm for help?
That's not how this server operates. If you have a question, you can ask it, with details, in a relevant channel and anyone who wishes to help will do so.
you can ask again if it gets buried
This works
Just to confirm, what you did essencially was get the relative position from hitPoint from the targetObject and turn it into dir
then project dir on the axis handle's up vector
and get the relative position again through newPos?
Now it works as intended
But for some reason it's affecting ALL objects with this script
You're welcome
Thank you, i believe i have a nice understanding of what happened there, but still a bit unsure
Yes you get a direction by subtracting a position from another position
Planes are infinitely "wide" so I guess you are hitting the plane of both of those handles
This has me very confused, shouldn't my script component only afect it's direct parent?
Should probably do some kind of distance check and check which one is closer
Busy right now can't check out the code
Understandable, but the plane's only being created when i click one of them
Hello. I was trying to create an input manager script + basic movement script(called fps controller) in 3d. However, everytime I try to start it, I am getting an error. which I'll share in photo. Below are links to the two scripts.
https://hastebin.com/share/pugerogaqi.csharp
https://hastebin.com/share/zibirofazo.csharp
PlayerINputHandler line 62 is where the first error is
lookAction is null
you need to look at that in your script
How is it null?
lookAction = playerControls.FindActionMap(actionMapName).FindAction(look);
presumably this returned null
i.e. that action name doesn't exist in your actions asset
Is it case sensitive?
of course
make sure you have saved your asset too
and make sure there are no spaces in the name or something
It's on autosave
and that the correct actions asset is assigned
you need to look at the fuill errorr message
and look at the filename and line number of the error
There is no Camera attached to the Player game object, but a script is trying to access it. You probably need to add a camera to the game object Player, or the script needs to check if the component is attached before using it.
the fact there is a camera in your scene is not relevant
So maincamera has to be inside player?
Your code is getting the Camera component from this object. If this object has no Camera, this is null.
There's no requirement for this in general, only with the specific code you wrote, which expects the Camera component to be on the player object.
If you don't want to use the Camera component on this object, don't
Why don’t you just pass the component as a parameter instead?
I have to, otherwise how will I be able to use the look action?
Either this object is supposed to have a Camera on it, in which case you need to add one, or it doesn't need one, in which case you shout stop trying to access it
What if I changed it to Camera.main?
Sure, that would no longer be trying to read the Camera component of this object
it would instead be referencing a Camera on an object tagged MainCamera
Well, that brings me back to the original problem. lookAction is still null
Then whatever action map actionMapName is on whatever input asset playerControls refers to has no map named whatever value look is
Perhaps log those values right before that line so you can make sure they're what you expect
Nope what
Make sure you look at the inspector for the object this script is on too. The action names are serialized. So you might have changed it in the inspector
check inspector
True
I swear to God, I'm stupid
also not clear what it is you are saying you tried there
All I had to do was fix a typo in the inspector..
Hello everyone Im kinda short on time so ill ask this in bigger message.So i have project for university bout making mobile games,i have 2 problems SpriteRenderer updates in Menu but not as physical object https://youtu.be/b8YUfee_pzc?si=txIGHsLc3-HUOtWP&t=19256 (i timestamped video on this part) and here is code im using rn following tutorial GameManager: https://hastebin.com/share/esocofovuy.csharp
CharacterMenu: https://hastebin.com/share/kosemanupu.csharp
Weapon:https://hastebin.com/share/wudekiwone.csharp
Second problem is enemy not following player:
part of video bout enemy:
https://youtu.be/b8YUfee_pzc?si=X_idqVFXWJbaSuYg&t=15057
scripts
Enemy:https://hastebin.com/share/uyotivekov.csharp
Mover:https://hastebin.com/share/rimesefohu.csharp
2024 edit!
I've got a new course teaching multiplayer here on youtube! Check it out
https://www.youtube.com/playlist?list=PLmcbjnHce7Scovukpm2UbvBmhPKvM52uD
--- Livestream alert ----
I'm live every Saturday morning, come say hello
https://www.twitch.tv/n3rkmind
This is a full release of an Top Down RPG course made in Unity 2017
Here's a link ...
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
2024 edit!
I've got a new course teaching multiplayer here on youtube! Check it out
https://www.youtube.com/playlist?list=PLmcbjnHce7Scovukpm2UbvBmhPKvM52uD
--- Livestream alert ----
I'm live every Saturday morning, come say hello
https://www.twitch.tv/n3rkmind
This is a full release of an Top Down RPG course made in Unity 2017
Here's a link ...
@polar acorn @wintry quarry Thank you kindly for your help
Not sure what you mean by "SpriteRenderer updates in Menu but not as physical object". You've shown what should be happening, but not what is happening
Menu one updates but in game stays the same picture
as weapon sprite
instead of chaniging like on menu one
So, it's logging the name of the current sprite, and it's showing as staff_2. Since the object in the inspector shows a sprite of staff_1, one of two things is happening. Either spriteRenderer is not referring to this object, or something else is changing the sprite after the log occurs.
Since spriteRenderer is public, another script could be changing it, or calling SetWeaponLevel to change it back
Okay thanks(sry didnt make any kind of game in 7 years).Seems like puting it private doesnt change much so ill try to update SetWeaponLevel script
If it's private and nothing is giving you a compile error, then that would eliminate the possibility of something else changing spriteRenderer, so we can now eliminate the first possibility of it referring to a different object. That'd mean something else is changing it after the sprite change, back to Staff_1. SetWeaponLevel seems the most likely culprit, since it changes the sprite without logging anything
📃 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.
could it be LoadState of GameManager thats problem,sry not sure how to share code here
xd
The bot tells you how
You called up the bot, you just have to read what it says
public void LoadState(Scene s, LoadSceneMode mode)
{
SceneManager.sceneLoaded -= LoadState;
if (!PlayerPrefs.HasKey("SaveState"))
return;
Debug.Log("Load");
string[] data = PlayerPrefs.GetString("SaveState").Split('|');
gold = int.Parse(data[1]);
exp = int.Parse(data[2]);
if(GetCurrentLevel() != 0)
player.SetLevel(GetCurrentLevel());
weapon.SetWeaponLevel(int.Parse(data[3]));
}
This does call SetWeaponLevel. Consider adding a log to the function to find out what value you're setting it to
so it calls value of of state when player moves to another level or when i restart game.Seems like this isnt problem.Ill try to check other things.Thanks for your time anyway.
anyone knowns how to setup neovim to work with unity?
is there any good public varible turtorial or somthing like that cus i just dont understant it
what dont you understand?
Well, other than programming basics that'd be hard to help with
public just means its accessible in other scripts
but i cant ever get it in my other scripts
How are you trying to access these variables?
you just need a reference to your script then you access the variable
i wil look
public doesn't mean that you can access it from any other script in the engine, that'd be a mess on the backend
it just means that when you reference that specific script, you CAN read\write those variables
i delted that
but it was like or with Serileized field or a whole line that says where it was and than what var
hey can anyone help me know how to make the Y axis of the pipe in Flappy bird change once per every spawn
all you need to do is
public MyScript script; drag in the inspector
script.MyPublicVariable; to access the variable
It allows the variable to be accessed from another script. That's it
mine changes every update
then change it when you Instantiate
instead of in Update
ok will try
on each pipe you can just set a random Y in Start, or on the script where you instantiate
public MyScript script; what is what i dont understant you exactly
this is just a variable
its the same as public int myInt;
you can access public variables from each script, if the script has none, you cannot access the variables
this public can be either private or [SerializeField] private to show it in the inspector
what is MyScript
replace it with whatever script you want to access
Your Script
yo, my code is crashing unity whenever i run it (2d android game)
async Task SignUpWithUsernamePasswordAsync(string username, string password)
{
try
{
await AuthenticationService.Instance.SignUpWithUsernamePasswordAsync(username, password);
Debug.Log("SignUp is successful.");
}
catch (AuthenticationException ex)
{
Debug.LogError("Authentication Exception occurred.");
Debug.LogException(ex);
_errorText.text = ex.Message;
_errorText.gameObject.SetActive(true);
return;
}
catch (RequestFailedException ex)
{
Debug.LogError("Request Failed Exception occurred.");
Debug.LogException(ex);
_errorText.text = ex.Message;
_errorText.gameObject.SetActive(true);
return;
}
catch (Exception ex)
{
Debug.LogError("An unknown exception occurred.");
Debug.LogException(ex);
_errorText.text = "An unknown error occurred.";
_errorText.gameObject.SetActive(true);
return;
}
SceneManager.LoadScene(3);
}
its your script... its as simple as it gets
it can be a Rigidbody2D it can be a BoxCollider it can be anything that you want to reference
is my script the referentie script
The type of the object you want to reference
//first script
public float cookies;
public float carrots;
public float hamburgers;
//second script
public Firstscript _firstscript;
_firstscript.cookies/carrots/hamburgers // etc
its the script you want to reference, the one you want to get the public variable from
oke thx i did it a lot diffuculterer
any1?
if you do not understand what I wrote, best you learn
its been 2 minutes, be patient.
mb
_firstscript.cookies/carrots/hamburgers // etc you added this later did helped me
im glad it helped you but its still best to !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i tried but it was the realy basics for a long time and i wout cus in my head it was to easy
Which Debug.LogError is running? You can't expect someone to just guess these things.
what? you tried it and it was to easy?
you do understand its a course right?
the first how what looked?
what does that even mean
"Too easy" is rich coming from someone who didn't know what a variable type was. Easy is what you need it seems
You are at the basics, so a video that goes over the basics is exactly your speed
and please elaborate what you mean by "the first how unity looked"?
i mean how to place things and change locations
you mean use public variables?
It is
Time to use Debug.Log to check for sure
i couldnt know since im not the greatest guesser
You're getting the seventh element of a list with 6 things in it
what
but the others worked like normal
arrays all work this way
Please tell me what "Element 6" is set to
this is the normal way
correct
no this is bolt back
5 is clipin
ohhh
sorry im dumb
i thought this was 1
so it was shoot
but i forgot to set it
yes it was 5
idk... as soon as i press the button that runs this code unity freezes (cant click on anything, log is frozen etc.)
so i cant see any errors in the log
Install the Logcat package, and run it while your phone is plugged in to see the console.
forgot to mention that im using unity editor
like the whole editor freezes bruh
i gotta kill it using task manager after
Then how do you know it's that code that is freezing it?
how to share code here?
!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.
cuz it freezes as soon as i press the button that runs the code
thanks
What does the button's code look like? Is it just calling ithat function?
https://paste.ofcode.org/4gMvHFaNTXmHf8eDen9cXF
can anyone pls tell me what is wrong here, I am not able to call the invoke repeat, It says
why did you put () in your string?
would removing it work?
yes
oops forgot this code (im sleepy)
public void SignUp()
{
if (IsValidEMail(_email.text))
{
string passwordCheck = IsValidPassword(_password.text);
if (passwordCheck == "valalaid")
{
Debug.Log("egg");
SignUpWithUsernamePasswordAsync(_email.text, _password.text);
}
else
{
_errorText.text = passwordCheck; // Set the text to the new value
_errorText.gameObject.SetActive(true); // Show the text
}
}
else
{
_errorText.text = "Invalid email format."; // Show error message for invalid email
_errorText.gameObject.SetActive(true);
}
}
Always look at examples to see how to use things https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html @viscid needle
You do not have a function named spawnPipe(). That would look like public void spawnPipe()()
removing the code from the button?
he was not talking to you
oops i thought u where other guy
yeah i realised...
This code doesn't go straight to the function you think is breaking. You're also checking if the IsValidEmail and IsValidPassword which itself can be an issue. Does any of your logs appear in the console before it freezes?
There's a few functions here that we don't know about, try commenting out the SignUpWithUsernamePasswordAsync function and see if it still dies
the last log is the Debug.Log("egg"); (dont question my names 😭 )
imma try that
yep doesnt crash now
and it only logs the egg
Can you log AuthenticationService.Instance at the top of the function?
So you can verify that you actually have a reference to it
hey umm... dum question but that code should spawn the pipeSet every 2 seconds and like 0.3 times right?
you mean comment it?
@frosty hound can you help,pls?
You are calling INvokeRepeating in Update, which means every frame you are going to start a new set of repeating invokes
very quickly it's going to get out of hand
It will wait 2 seconds to call it the first time, then 0.3 seconds for each. Every frame you start a new set
ohh thanks
So, after 2 seconds, you will be spawning one every frame
No, people shouldn't be answering question you can just test yourself.
and you'll have your answer.
sry
thanks
if i comment out the authenticationservice.instance.SignInWithUsernamePasswordAsync thing it doesnt crash, logging it as you said outputs: Unity.Services.Authentication.AuthenticationServiceInternal
and then it proceeds to do the sign up succesful stuff
That's not at all what I asked?
I asked it
Just to confirm if it was that function and not the other IsVald___ functions
you asked to do Debug.Log (AuthenticationService.Instance);
which i did
and i commented out the signinwithusernamepasswordasync so it doesnt crash
and this logged Unity.Services.Authentication.AuthenticationServiceInternal
hey umm... my pipeSet's Y value us changing every instant, I want it to change with every instantiate how do I do that
How are you changing it
instead of doing it however you're doing it now, just do it when you spawn a pipe.
how?
So, every time spawnPipe is called, you move whatever object pipeSet is
Is that what you want spawnPipe to be doing?
I am trying to make flappy birds pipes bro
by writing the code there
That doesn't answer my question
this code isn't spawning anything
it's jsut moving some existing object
Yes to the left but I want it to spawn at different Y cordinate at every instantiate
that would go in the code that spawns pipes. You are looking at the code that moves pipes
So, you want your function named spawnPipe to move an existing object to somewhere else?
Ik i have been trying to add the instantiate command but it just shows a error
If so, you should probably call the function something else
You are confusing this shit out of yourself
you dont need to instantiate anything again
why are you doing this in the "moveLeft" script
to the left endlessly
You need to look at the script that actually spawns things
this is the script that moves the pipes
I had named it previoulsy tha
Okay, so why is the function called spawnPipe
fix your script and function names to stop confusing yourself
You should name the functions what they actually do
Okay, so pipeSetSpawn is a function that moves pipeSet
Still doesn't make much sense
can we please ignore the naming for now pls (I am very sleepy)
The fact that this is your second attempt at naming it shows that you don't seem to know what that line of code does
pipemove would be better
What do you think this line of code does:
pipeSet.transform.Translate(-1f, Random.Range(-4f, 4f), 0);
I want it to perform the task I am naming it but struggling
did it
If you want it to spawn something, it should probably actually spawn something. Right now, you are moving an object
so how do instantiate it
ok I will try to understand it again
hey how can i check if all my referenced colliders (trigger) enter my other collider?
i need it for my placing system which checks if all "anchors" touch the floor
Probably easiest to do an OverlapBox/Sphere/Capsule/Circle2D for each of those
Actually not OverlapX but CheckX
you could also use the triggers ontriggerenter to check if any objects go in it
You can also manually check it in OnTriggerEnter/Exit but that sounds like more work
but i want to check if all of them enter not any
Since you need to keep track of each collider, as opposed to instantly checking it with a physics query
what?
okay then check for that
just use an array or list or smth
I do not see the need for hostility
I'm saying, do a physics query (for example Physics.OverlapSphere) on the points you need to check
hi i added my freind to my orginization so we can work on a game togather how can he accses it from the unity hub he can see it on the cloud but there is not option in the hub
please help us so we will be able to work on a game togather
In that case you wouldn't really need to have colliders though, but it would be good to visualize the required areas with Gizmos
The other option is to add each collider into a list in OnTriggerEnter and remove it in Exit
And when you want to place the object, check if the list has all of the colliders
how do i check for the list?
public List<GameObject> ListObjects = new List<GameObject>();
this is to create it
then you just do a for/while loop and check if there are more than x amount then do something
make sure you do List.add to add things to it
also keep in mind i am not the best at lists 😅
but cant i just create a list like this: public List<BoxCollider> Colliders; and add the colliders in the inspector? also i meant like how do i check if all the colliders in the list collide with my other collider
hey can anyone pls help me how to finish this codehttps://paste.ofcode.org/VBRBVEEFtBUcx6ZcMDYB4M
it has something to do with angles I just dont know what
I have to fill it with a quartanion rotation
the rotaions are supposed to be all 0, pls help fasttt
Hello, im working on a 2D game and in it I am spawning "pillar" gameObjects for the player to walk around, currently I am tracking its sorting order and putting it above player if behind it and below if its infront like so:
void Update()
{
if (player.transform.position.y > transform.position.y)
{
//Player is above Pillar
this.GetComponent<Renderer>().sortingOrder = 1;
}
else
this.GetComponent<Renderer>().sortingOrder = -1;
}
The issue is when I have to pillars next to eachother they still clip, I was hoping someone could tell me the best approach to fix that, my current thinking is to also check in this function for adjacent pillars and change the sorting order accordingly
hey can anyone pls help me how to finish this codehttps://paste.ofcode.org/VBRBVEEFtBUcx6ZcMDYB4M
it has something to do with angles I just dont know what
I have to fill it with a quartanion rotation
the rotaions are supposed to be all 0, pls help fasttt
well yes you could, and you can do that with a list as well, so best you use what Osmal said #💻┃code-beginner message
still dont actually get what he meant but is there no direct way to check if every collider hit my other collider?
As Osmal pointed out, the easiest way to do it is with Physics.CheckBox. Here's a simple example:
bool CheckAnchors(Vector3[] anchorPositions, Vector3 halfExtents, int groundLayermask)
{
foreach(Vector3 anchorPosition in anchorPositions)
{
if (!Physics.CheckBox(anchorPosition, halfExtents, layermask:groundLayermask))
{
return false; // Anchor not touching ground, no need to check the rest.
}
}
return true;
} ```
There is, each anchor collider needs to check for collisions separately and "send a message" to some sort of an "anchor manager" whether they become grounded or not, with the anchor manager keeping track of the grounded anchors count.
thats what overlapsphere/box/etc does, you check if it hits a collider with a specific tag and add it to the list. if this is over or equal to a certain amount and those objects also have a certain tag then do something
can i just do it with a child for each collider?
can you use overlapsphere/box/etc to check a gameobjects child?
physics queries don't care at all about the object hierarchy
can i just check for the name of the childs?
they will tell you which colliders overlap, full stop
Thankyou, this seems like what I need however when I go into my project settings theres no camera settings under graphics
well you could check for names but thats not recommended
scroll down in the thread, and make sure you're looking at the stuff for the appropriate render pipeline
why not?
thats why i suggested tags, which are not that better but are good for what you want
very slow, causes garbage collection, and is just... not the way. references are better in every way basically
Apologies for being an idiot 🫡
how can i even give a tag to a collider
you give a tag to a gameobject
bro what the actual f do you mean
Mate you should drop the attitude if you want help here
how does it help in any way to determine if everyone of the colliders entered collider "whatever" if i give the same tag to all of them?
sry im tired
I don't know about the tags, I didn't suggest that. I suggested using lists which you ignored
you check if the gameobject has the tag and if it does you add that gameobject to the list
i explained it a while ago
it's not good to develop when tired, mistakes are more likely
there is definitely better way instead of tags but i dont know them rn
i created a list with my colliders but i have no idea what to do with it exactly
This
But I personally would do this
oohh havent seen that one yeah this makes sense. ill try it
Apologies if im asking too much but would you mind explaining to me what I just did? It took like 2 seconds and works like magic, I don't even think I need my initial code anymore right?
https://www.youtube.com/watch?v=O30iPjskZ18
Can anyone explain to me why i cannot put gameObjects into a Prefab, but when it is in Hierachy i can? How can i fix this so i dont have to have everything in my Hierarchy?
you don't need the code no
it's a project setting that changes how the camera renders your sprites. It sorts them in order by the y axis
I think your issue is that you're parameter is a transform when your prefab doesnt exist in your game world so wouldnt have a transform
Thats like magic to me, thankyou so much for your help I cant believe it could be that easy
So that means, because it is not spawned/loaded yet, it cannot take any Transform attributes since its technically not in the game?
becasue assets cannot refer to objects in a scene.
You need to get the reference another way
for example, assign it at reference in your code after spawning the object
like in Awake()?
no like in the code that spawns the object
ah okay thanks!
MyScript spawnedObj = Instantiate(myPrefab);
spawnedObj.someReference = aReferenceIHave;```
hi i was wondering how to make a colidor move with animation?
You could animate its transform or collider's center property
What is this for though? Not sure if it can reliably produce collisions for you if you move it with anims
you can also make primitives as children of each bone as well
if you are talking about a moving mesh collider, just no
its for my player im prety new to unity si i jast took a free charhachter and animation so i dont know how to edit it so it will move the transform
If you do not know what transforms are or dont know how to move them I suggest you !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
But as Osmal said this may not produce good collisions
i do i jast dont know what it means edditing the transform
Do you know what a vector3 is?
semwhat
I suggest you learn via link
ok ty
Hello again, I'm trying to create a boolean variable to allow my player character to be deactived and reactivated, but i don't know what to put in the coding to define how to define the true and false of this boolean https://hastebin.com/share/izodetiwid.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Good evening. I am still quite new to the subject. But I would love to create my own mobile game. It should be a kind of AFK RPG. Could someone kindly tell me what I need for it?
AFK RPG? like doing nothing?
but for an RPG you would have to ask yourself what you need, what you want the game to look like, etc
youre trying to set a boolean as a gameobject, which will not work
some more info on what youre trying to do exactly would be nice
or how youre trying to achive this
A GameObject is not a Boolean
i didnt know that even existed 😂
If you're starting from literally zero, with no knowledge of the program or anything, go through the first few pathways on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!

Idle games are actually a non-trivial problem, you'll learn things like data persistence, real time synchronization, and how to handle numbers too big to fit in a float. Still, it's not an insurmountable goal for a first project, it's not massive in scope, it just has some quirky technical problems other game genres don't
ty
wait wait, so this exists?
like AFK games? (oh you mean idle games nvm then)
I am literally playing Cookie Clicker right now
that will most likely destroy your sanity
and or your attention span
Just wondering, is it possible to use DOTs to just spawn specific things and use 'regular' Instantiating etc. for other things? (essentially mixing the two methods)
what is this thing that keeps appearing even when i delete it
The thing that makes your UI work
Do you want your UI to work
probably
Then you probably want to stop deleting it
good idea
that is the plan
How can I tell what objects are being considered as obstacles for a navmesh?
If they have an obstacle component, then they are considered obstacles
Ah, right so I can search for those
Interesting. So originally I was using a navmeshmodifier to achieve the result of the obstacle (with carve on). Had to end up switching that because there doesn't seem to be a reference to it I can get via script? Edit: it might be entirely possible that I'm missing a using statement, since modifiers require an additional install.
This does beg the question. What exactly is the point/difference between the two?
Modifiers change what is considered a navmesh at baking time iirc. Obstacles are modifying the navmesh at real time or even just affecting the agents dynamic pathfinding(avoiding things when it moves by them).
Interesting. Is it possible to retrieve these modifiers via script? I didn't see any option pop up with intellisense
Don't trust a stranger though, read the docs
Should be possible. Check the docs or inspector debug mode to see what type it is.
From the looks of it, I should be using obstacles. Modifiers seem to be for more interesting changes to the navmesh. The example used in the docs is a "lava" area, rather than something like a wall
If the wall is static and never gonna change, I think you should use a modifier
Using a modifier with a non-walkable area override should do it
Gotcha, my problem now is trying to reach the modifier component via script. The docs are proving to be a maze on this.
That's the old navmesh package, are you using the new one? It's this https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/index.html
Try UnityEngine.AI.NavMeshModifier ?
check if the package osmal has linked is installed in the package manager
if its not, install it
I implemented all this so now I just need to know how to get it to make a new random point if the dot is < 0
Oh, is this the old version?
What unity version are you using? There's a change in the API in 2022(I think) as the navmesh is now package based.
Do a for loop, with something like i < maxTries
When you find a valid position, break out of the loop
If with "dot is < 0" you mean it's in an undesirable direction
It is the right package, but an old version (1.1.5 vs 2.0+)
Weird. I didn't download this that long ago. Must've picked it up from an older area. Where can I get this newer version?
You can't it seems. What unity version are you using?
what unity version are you on?
If it's older than 2022, you should probably upgrade
2.0 is 2023.2.0a18+
2022.3.16f1
Actually I'm on 2021 and not using that package lol, so it's probably not even supposed to be UnityEngine.AI.NavMeshX
Shouldn't Unity.AI be enough to get that?
No
what IDE are you using? usually you can let your IDE auto import the needed stuff
Unless you explicitly use Navigation.NavMeshModifier every time.
Not UnityEngine.AI
Yeah the old package was in UnityEngine.AI.
angery
The IDE sees it now
Ty all for helping me on this
What is the area type in nav mesh modifiers? I see it's an int, but the values you see in the editor are, well, words. Is this like a layer mask or something?
It's an integer but displayed as the name of the area
in the inspector you see a nice dropdown yea
And in some places - such as what Praetor linked - it's a mask so sort of similiar to layermask yeah
Gotcha. Trying to see how to implement this in a way that's readable, instead of plopping a magic number and calling it a day XD
Try NavMesh.GetAreaFromName
Is there an "AreaMask" type like there is "LayerMask"? Not getting AreaMask to show up in intellisense
Dont think so, just an integer
This would require using UnityEngine.AI, which is older, no?
Or is it okay to combine the functionalities of the old system with the new(ish) ai.navigation?
I think it still uses parts of the navmesh class but I could be wrong
Doesnt it use the same systems for configuring area names, costs etc?
Hello, can someone help me with very basic things? I don't know hoe to explain the problem with text so I would like to show
It might? I'll toy around and see what I can do
Do your best to explain/show it and people can take a look
Interesting, it actually seems to work. That's kind of cursed I'm mixing two different versions of a similar thing together XD
float moveX = 0f;
float moveY = 0f;
//Sprinting.--------------------------------------------------------------
if (Input.GetKey(KeyCode.LeftShift) && stamina >= 2.2f && rb.velocity.magnitude > 0)
{
//getting camera animation----
animator.SetTrigger("Running");
//speed becomes boostedSpeed----
speed = speedBoost;
//reducing stamina on cost of runcost---
stamina -= runCost * Time.deltaTime;
if (stamina < 0) stamina = 0;
staminaBar.fillAmount = stamina / maxStamina;
//new Color(234, 244, 84) - normal color.
//run - new Color(187, 194, 79) - sprint color.
staminaBar.color = new Color(187f / 255, 194f / 255, 79f / 255);
//reseting Coroutine----
if (recharge != null) StopCoroutine(recharge);
recharge = StartCoroutine(RechargeStamina());
}
else
{
animator.SetTrigger("EndRunning");
speed = 30f;
}
//StaminaBar Color Configuration.------------------
if (stamina <= 0)
{
staminaBar.color = new Color(131f / 255, 132f / 255, 120f / 255);
}
else if (!Input.GetKey(KeyCode.LeftShift) && stamina > 2.2f)
{
staminaBar.color = new Color(234f / 255, 244f / 255, 84f / 255);
}
//Movement On Keys.------------------------------
if (Input.GetKey(KeyCode.W)) moveY = +1f;
if (Input.GetKey(KeyCode.S)) moveY = -1f;
if (Input.GetKey(KeyCode.A)) moveX = -1f;
if (Input.GetKey(KeyCode.D)) moveX = +1f;
//PlayerMovement.----------------------------------------
Vector3 moveDir = new Vector3(moveX, moveY, 0f).normalized;
Vector2 targetVelocity = moveDir * speed; // your movedirection * speed
Vector2 velocityDiff = targetVelocity - rb.velocity;
rb.AddForce(velocityDiff * acceleration);```
Hello, How could I fix this jittering guys, sometimes it looks smooth but in the end its kinda weird.
The NavMesh class is still relevant.
The "old" version is just the NavMeshComponents package that you had yo manually download. The NavMesh itself predates that
turn on interpolation for your RIgidbody2d
Ah ok, nvm on my last comment then
if (PlayerRotates)
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}```
because you're directly modifying the Transform here, you're breaking the interpolation
How are you rotating the rb?
Ah there we go
with extrapolation
mouse rotation?
I have an object in root with Transform and basic Shooter script that takes bullet prefab and instantiate it giving the bullet velocity and parenting it to itself. In the play mod I dragged it on the scene to see what s happening and saw that it jiggering its position in scene tho in the inspector it is not
Vector3 lookDir = mousePos - transform.position;
rb.rotation = Mathf.Atan2(lookDir.y, lookDir.z) * Mathf.Rad2Deg;```
this is what you want
Okay wait I'll try and implement
Wouldnt that be MoveRotation?
if (Input.GetKeyDown(KeyCode.X)) { if (PlayerRotates) PlayerRotates = false; else PlayerRotates = true; }
//Player Rotate Follows Mouse.---------------------------------------------------------------
if (PlayerRotates)
{
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 lookDir = mousePos - transform.position;
rb.rotation = Mathf.Atan2(lookDir.y, lookDir.z) * Mathf.Rad2Deg;
//transform.rotation = Quaternion.LookRotation(Vector3.forward, mousePos - transform.position);
}```
So like this?
yesd
Or does rb.rotation not break interpolation
it doesn't break interpolation
Should I use inter or exterpolation
interpolation
Extrapolation kind of overshoots, trying to guess where you should be
While interpolation just lerps between the last and current position
Could be a camera issue too 🤔
You probably have an issue with your camera now
how are you doing camera folow
show the brain
make sure the brain is in LateUpdate or SmartUpdate mode
you have to have a brain
where tf is brain i dont even know
it's on the camera
Is there some way I can reach into these AreaMasks, so I can record the list of them?
yeah discovered
ok that should be fine...
double check the player inspector?
Do a for loop from 0 to 31
do someone know why is it jiggering?
also try disabling the rotation code for a sec to see if it does anything?
ok
Iterating over what though is the issue I'm having
Probably because your code is positioning the object late
Also set this to pivot
What info do you want to store about the areas? @waxen adder
ok try putting the mouse look code in FixedUpdate and using rb.MoveRotation instead
Alright wait
Just their name and index. I'm gonna be honest, not a big fan of how these are set up, so was going to create my own data type for them
rb.MoveRotation(Mathf.Atan2(lookDir.y, lookDir.z) * Mathf.Rad2Deg);
like this?
yes
ah yeah that was the issue, thanks
Actually I dont see a way to get area name from index, at least in the NavMesh class. I only see GetAreaCost
Oh. Hmm. That changes things
leave this part in Update
and?
Meh, I think I'll just keep things simple and do area comparisons with GetAreaFromName
by default it's true so
that should do it..
that didn't do it
is SHould Rotate printing?
yes u can see
show the rest of the code?
(clicking X to toggle too)
How to post !code (use the large code blocks section)
📃 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.
maybe the Animator is interfering now? 🤔
how would it
Animator only triggers on Shift
see if disabling the animator does anything
Ok i'll try that
I think this should be Y and X, not Y and Z
I'll try that too wait
oh yeah
you don't have the rotation constrained do you?
yeah I don't even know what that is
add 90 to it
rb.rotation = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 90;
possibly subtracting 90 lol
one of those
actually
I did this haha
rb.rotation = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg + 270;
- 90 would work
Yeah thats the same as -90
I think my math is mathing rn so I understand that last part
yeah
since this is learning process maybe could u guys like explain what was going on?
a little?
to not waste ur time much
you didn't have interpolation on your rigidbody, so you got stuttering
because the physics engine runs out of sync with the framerate of the game
interpolation smooths that
but if you directly modify the Transform, it breaks the interpolation
so we just had to make sure you had interpolation on and you weren't breaking it
what does Extrapolation do
if you moouse over them there's a little explanation
interpolation is a little behind, extrapolation is a little in the future
both smooth it out
and what about uh
Moving code to Fixed update
I know difference that
Update runs more frames and that
was it like necessary to move the rotation code to fixedUpdate?
for MoveRotation it is
Extrapolation goes better with Update
However its opossite for interpolation
(tested it out)
my understanding is .rotation would go better in Update and MoveRotation would go better in FixedUpdate
im using .rotation in fixedupdate and it works best
so my understanding may be off. Maybe it's different for 2D
So would this work same for that stick? should I put interpolate on it too right
just did and it worked! thank you so much <3
Another question. I have an Object that have "Gravity" script attached:
private float _gravity = -10f;
private Rigidbody2D rb => GetComponent<Rigidbody2D>();
void Start() {
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y + gravity);
}```
"gravity" is -10. So the object at default have y velocity -10.
And it have another object as a child that spawns objects and giving them x velocity via "Speed" script attached to this objects.:
```cs
...
[SerializeField] private GameObject projectile;
public Vector2 direction = new Vector2(1, 0);
...
GameObject _proj = Instantiate(projectile);
_proj.transform.parent = transform;
_proj.transform.localPosition = Vector2.zero;
Speed _projSpeed = _proj.GetComponent<Speed>();
_projSpeed.horizontalSpeed *= direction.x;
_projSpeed.verticalSpeed *= direction.y;```
The "Speed" script:
```cs
public float verticalSpeed = 0f;
public float horizontalSpeed = 0f;
private Rigidbody2D rb => GetComponent<Rigidbody2D>();
void Start() {
rb.velocity = new Vector2(rb.velocity.x + horizontalSpeed, rb.velocity.y + verticalSpeed);
}```
The issue is that instantiated objects have the velocity, but they don't moving at all. They move when they attached from its parent tho, is this because the parent is changing it's position via velocity? If so, how do I make children attach to it but have velocity and move as expected?
Try making the rigidbody not kinematic
Not sure how the rb acts when it's a child though, especially if the parent is moving. I usually avoid that
Ah, 2D kinematic bodies can be moved by velocity so that part should be good
That helps, but I afraid that could affect the perfomance too much?
What helped? Making it not kinematic?
Yeah, I made projects dinamic
but if there are a lot of them
it could affect perfomance Im afraid
Why would the docs say that kinematic rb2d can be moved by velocity 🤔 I wonder if thats even correct
it is moving, but only if it independed
IIRC 3d bodies ignore velocity when kinematic so there is some inconsistency between 2d and 3d
Does the parent have a rigidbody?
yes
I dont see why you need them as children
Alright, maybe keep them separate and yeah destroy them from a list
Another option is to give the player an empty parent that acts as the container for everything related to the player
Then destroy that parent
I also want them to move with its parent, and feel like there will be alot of unnecesery code if I attach them
And have the bullets directly as children of the parent. So "siblings" of the player
they are probably different due to the fact they use different physics engines
if not then idk lmao
Sure, its just confusing that kinematic means different things
Unity could name things anything they want regardless of the underlying physics engine
its all a facade
You might have to make them follow the player manually then. Not sure though, maybe there's a way to make it work. I mostly use 3D
Generally speaking rigidbodies shouldnt be children of other rigidbodies
Unless the child is kinematic
yeah I got it,
I'm trying to make a simple script where when I press R the object's Y rotation value goes back to 0, I have made this code so far but it says "The name 'gameObj' does not exist in the current context" how would I go about defining it?
public class Resetcar : MonoBehaviour
{
void Update()
{
if (Input.GetKey(KeyCode.R))
{
gameObj.transform.eulerAngles.y = 0;
}
}
}
did you mean gameObject?
But also you don't need that at all
Vector3 eulers = transform.eulerAngles;
transform.eulerAngles = new Vector3(eulers.x, 0, eulers.z);```
gameObject would be redundant here
Yeah that fixed it, thanks a lot
float LastFrameTheNavmeshWasUpdated;
public void UpdateNavmesh()
{
if(LastFrameTheNavmeshWasUpdated != Time.frameCount)
{
LastFrameTheNavmeshWasUpdated = Time.frameCount;
StartCoroutine(NavmeshUpdateCoroutine());
}
}```any better pattern to make sure this coroutine doesnt run multiple times no matter how many times it was called in a single frame?
where are you running UpdateNavmesh?
multiple scripts that affects the map
usually when some obstacle was built/destroyed
because frameCount is an int
oh yes, lemma change that
but yea, is this the best pattern?
I tried flipping a bool and checking in Update() but that was probably worse, is it?
Another option is:
bool shouldUpdateNavMesh;
public void UpdateNavmesh() {
shouldUpdateNavMesh = true;
}
void LateUpdate() {
if (shouldUpdateNavMesh) StartCoroutine(NavmeshUpdateCoroutine());
shouldUpdateNavMesh = false;
}```
whgat you have now is fine I would say
Also you're 🤏 close to 300k (I dunno how you can be so active, I barely added 7k messages on one of the server I am usually staying in)
I have 7k to go, which is your whole chat history
Hi
can anyone help me, im having an issue when my character walks into a wall it slightly changes its rotation, my game is 2D, how do i fix this?
don't crosspost
someone else gave me the solution, i needed to constrain the rotation in the rigidbody
that was me
whoops 😭
Using the line renderer i have drawn Lines. The line renderer is on a UI Object in the Canvas and i want the lines to either follow the camera or the object its attached to but if i turn off world space the lines will no longer render and im unsure what to do?
you can change the Canvas to use "World Space" instead of "Screen Space" (then position the line renderer)
Is there a way to make if statement that will trigger on collision with objects of all tags but not one specific?
i was told in the past that this didnt exist! ive been lied to!
compare the one you dont want and do nothing, and in the else statement, do what you want
it says it's a static string though. surely that means it can't be changed? or am I mistaken
static variables can be changed, it just means the value doesnt get reset when the instance of the script is destroyed
oh right. I've learnt something new today! I was probably thinking of const as something that was non changing
thanks
Why must i do float x = 10f instead of float x = 10?
it feels redundant since I already specify float
Think about it like this: why can't you do float x = true; ? The same reason applies here
you can. you cannot do
float x = 1.1;
because 1.1 is a double and you cannot automatically downcast
Good question, I've never had to use f in C/C++ every time I was defining a float. I don't know if you have to do it in those languages too (if yes, then it's just a legacy from those languages), if not, there must be a reason why they chose to do it that way at Microsoft. Maybe it's to differentiate between float and double, as historically floats are using IEEE754 on 32 bits, whereas doubles are using IEEE754 on 64 bits. Nonetheless the compiler should be able to detect from the type itself.
Probably this.
Decimal values may be defaulted to double.
they are
I'm just wondering why the f isn't strictly mandatory in C/C++
because C and C++ are not type safe, C# is
The same behavior applies to those languages, but they implicitly cast to float whenever you assign something to a float. Microsoft decided to not implement this indeed
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions
In C#, you can perform the following kinds of conversions: Implicit conversions: No special syntax is required because the conversion always succeeds and no data is lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
C and C++ do not care about data types. you can declare a variable as a long and use it as a double, the only thing that matters is the size of the type
From double to float, data is lost
may be lost, it's basically a warning to say 'Do you really want to do this?' A very good thing imo
Data loss prevention. Even though this is clearly not the case here, so I agree it's kind of weird. Either way it's consistent
Yes, they chose safety, not a bad thing imo
number of times I've had to debug bad C++ because of unintentional downcasts
Also, my guess the reason why you do it here and not with things like integers is because of floating point inaccuracies
So explicitly specifying ensures this is not the case
Is C# using a whole environment to run? (Like Java's VM)
yes, the .Net runtime
Hi, does anybody know how i can make the yellow UI image be under/behind the gray UI image? I've tried changing the z positions but had no luck. Thanks
Do i have to make seperate layers?
not a code question. but UI is drawn in the order it is in the hierarchy, so things higher up the hierarchy are drawn first, which means lower in the hierarchy are drawn last (or on top)
ah, thought this channel was for unity beginners in general. Thanks for the help
nope, the code in code-beginner means it is a code channel
oh really, i would have never guessed that
in the calculator, I wanted to make one which can solve numbers without taking a big if chain for 2 numbers.
answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
this shows error that I can not convert dbnull into double.
i imported system.data into assets and gave reference.
public class Clac : MonoBehaviour
{
public TextMeshProUGUI disptext;
private string CurInput="";
private double answer;
public void ButtonTap(string val)
{
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
CurInput=val;
UpdateDisplay();
}
}
public void ans()
{
try
{
answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
CurInput=answer.ToString();
UpdateDisplay();
}
catch(System.Exception)
{
CurInput="invalid";
UpdateDisplay();
}
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}```
if i remove try and catch exception, the code gives that error
with this, it simply says invalid
how do you guys make your code like that in discord
!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.
!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.
'''cs
//void FixedUpdate()
{
Vector3 playerInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
transform.position = transform.position + playerInput * speed * Time.deltaTime;
Vector3 playerJump = new Vector3(0, Input.GetAxisRaw("Jump"), 0);
transform.position = transform.position + playerJump * jumpForce * Time.deltaTime;
}
'''
u used ', use ` thrice at the top and then at bottom
Did you actually read the DataTable docs?
bottom too
he just has to read the bot
they are backticks. the tilde key (on an american keyboard) . . .
i watched a tutorial and tried to understand the code(I know python so i assumed its like a dbms)
// void FixedUpdate()
{
Vector3 playerInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
transform.position = transform.position + playerInput * speed * Time.deltaTime;
Vector3 playerJump = new Vector3(0, Input.GetAxisRaw("Jump"), 0);
transform.position = transform.position + playerJump * jumpForce * Time.deltaTime;
}
lets go i did it
well looking at your code, a couple of things, put inputs in Update() so they wont mess up or act jittery and as far as your movement being floaty, im guessing just make your gravity larger
well, I would suggest you go and read the docs before trying to implement something you know nothing about
also you are manually manipulating the transform of an object
i forgot to mention the when i let go of space bar my characters gravity is effected more somehow
and applying it by time.daltatime
you're manually manipulating the transform but you have a problem with gravity?
yes you are
i am?
any reference websites? I also have this as an assignment so gimme a quick help if possible lol
your player doesnt respect gravity from what im seeing
you are setting the transform.position; this is manipulating the transform, which does not involve the physics engine at all . . .
when i start the game my player still falls though
and if i manipulate the gravity is falls faster
so you have a rigibody
then use its Addforce() or Velocity to move around
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody2D rb;
public float speed;
public float jumpForce;
public float gravityForce;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Vector3 playerInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
transform.position = transform.position + playerInput * speed * Time.deltaTime;
Vector3 playerJump = new Vector3(0, Input.GetAxisRaw("Jump"), 0);
transform.position = transform.position + playerJump * jumpForce * Time.deltaTime;
}
}
thats all my code
using \ isnt necessary
\ \
gravityForce does nothing i forgot to delete that
so what do i do if i cant used datatable? any alternatives to immediately solve the problems without 3 massive if chains?
okay first off as i said put inputs in Update() and use the rigidbodies Addforce() and or Velocity to move around
best you !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
{
lastPos = controller.transform.position;
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
move = transform.right * x + transform.forward * z;
controller.Move(speed * Time.deltaTime * move);
}
I've got this code here. Is there any way I could only check the x and z of the controller instead of the entire 3d vector?
I don't even know what your 'problem' is as you have never specified it
but addforce isnt that responsive i want my game to be responsive, and i though FixedUpdate is better for physics?
yes by making a new vector with all of the parameters you need
just access the x and z axes or create a new vector with only the x and z values . . .
Addforce is responsive you just need to know how to use it, but in your case it looks like you want to use its Velocity. FixedUpdate() is for physics system and is framerate independant
as i stated you really need to !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
yes, but you must use physics methods in FixedUpdate, like AddForce and assigning the velocity property of the rigidbody . . .
so you are making a simple calculator?
yes
also NO inputs should go in FixedUpdate() unless you want a stuttery mess, best put them in Update()
then you jst need a simple string parser
thank you
For example. I want to check if x,z of last pos != move.transform.position
will parse or tryparse work similar to compute? or do i use compute whilst using parse?
make a new vector with your transforms X and Z values
no, completely the wrong direction.
First you need to split your string into an array using the operands
then you can turn the string array into a number array
then you can apply the operands to get your answer
and use said vector
wouldn't that take just 2 inputs?
I have no idea how to define it correctly. I was trying to do lastpos = (x, 0f, z) but I'm getting an error
why, it can take as many inputs as you want
until they hit =
k, im gonna try it out
lastpos = new Vector3(controller.transform.position.x , 0 , controller.transform.position.z);
you assign it a new vector
Thank you!
but i would suggest you !learn either by the link or by the documentation
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
am i supposed to use tokens tho?
you might like to look at https://stevesmith.software/lysei/
you might want want to keep the documentation in your bookmark menu
shameless plug 😂
Thanks for your advise
it's just something I played with years ago
of course
like a scientific calculator?
looks neat
equation solver
does it directly compute like cs answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
or does it use if statements for each operation and stops when it hits "="?
Hey, I wrote it, It's much cleverer than either of those
cool beans
for a beginner, debug.log() and some of the most complex games are equally cool lol
mb yo
hard work, took me all of 3 hours to write
you were slaving away at that program
i think asking chatgpt for help was a massive mistake
thats why we dont recommend it
no surprise there
it overcomplicated the code and i already forgot what i know
welp better luck next time, dont use it
the more i ask it to do it beginner style, the more it complicates itself
stop asking it
also, does dangling else work in c#
you literally have your own server to ask in
i once found a guy who was like a pro and was explaining about me using function and methods(wasnt aware of what it is) and i was barely understanding anything
well he was explaining it?
so he should have explained it to your level then
had to ask him to explain how he would explain to a 5 year old
well my point still stands, best not use gpt
you have what, like 20,000 people in here?
i can assuredly say to you that gpt is nothing compared to that
this is a code channel, where's the code relation in your question? if none, delete and ask in #🔀┃art-asset-workflow
using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class Clac : MonoBehaviour
{
public TextMeshProUGUI disptext;
private string CurInput="";
private double answer;
public void ButtonTap(string val)
{
if(val== "=")
{
ans();
}
else if(val== "C")
{
Clear();
}
else
{
CurInput=val;
UpdateDisplay();
}
}
public void ans()
{
try
{
answer= System.Convert.ToDouble(new System.Data.DataTable().Compute(CurInput,""));
CurInput=answer.ToString();
UpdateDisplay();
}
catch(System.Exception)
{
CurInput="invalid";
UpdateDisplay();
}
}
public void Clear()
{
CurInput="";
answer=0.0;
UpdateDisplay();
}
public void UpdateDisplay()
{
disptext.text = CurInput;
}
}
Are there any errors with respect to unity?
why ask us when the console tells you
if you get any errors or warnings, the console will scream at you
It's also against the server rules to
- ask for help with code generated by AI
- give help to code generated by AI
its a tut code
is that also against the rules
If it's tutorial code... your question then doesn't make sense. 😄
its really bad code either way
it makes no sense and abuses things that will just makes it harder to find bugs
like that try catch will just mask what is going on
and is like the worst way to convert a string to double
does writing a code in vs and vsc differ by any means?
its jsut a tool to write code, all code unity sees compiles the same way
k, tnx
VS is better than VSC, if you have the choice
realy does not matter for most, what ever is easier to get setup is what i would go with
What’s the write approach to start programming as a beginner
Just an editor, one may become handier than another depending on what you're looking for, I personally prefer vscode as it's lightweight, and supports every language because it's just a text editor. You can configure it to mimick a real editor designed for specific languages but yeah
i learnt html-->python-->sql-->C-->C#
i forgot evrything abt html
but yea python is good for base and C
learning either is easy
C is very good to understand memory and how things work
id prefer c
C seems easy but it can become a hassle as it lets you do whatever you want
C# is the better looking java
There is no correct approach.
You do what works for you.
learn the langauge that does the thing you want to do
no point going through a whole path, if you all you want to do is make a game that uses C# or C++
you will learn more if you can apply the skills to a project you care about and find intersting then just going through the motions