#💻┃code-beginner
1 messages · Page 662 of 1
Just Alt-Enter (show potential fixes) in your screenshot, and import the appropriate namespace
i didnt have using system.collections
ye i did
wierd
thought that was adefault
mightve accidentally deleted it
anyways have a good night
not in U6
hello
anyone mind trying to help me with a specific script
the idea is
that theres a distance between a empty gameobject and the player as a float
and if the player is in that distance and they click f, one object is set active and the other one is set inactive
but when i go close it doesnt do anything
i can give the script too
No, it's short for Unity 6. The hub is not relevant for creation of anything within the project (after initial project creation)
help please?
theyll get to you
rightio
don't ping people not in conversation with you.
also probably dont offer to share the script and just share it
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
holy shit bro
i lit went into a channel
and i just said
that i already did all this
did you read the whole thing
all?
the ask stuff
all of them? are you sure?
read the last line
i could probably find some results real wuick
Whine less
why would you get muted for sending your script, just send it
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
that happened
before to me
cuz i "flooded"
Which you are still doing.
using UnityEngine;
public class Door : MonoBehaviour
{
public GameObject maindoor;
public GameObject closeddoor;
public GameObject opendoor;
public GameObject player;
private bool IsOpen = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
opendoor.SetActive(false);
closeddoor.SetActive(true);
}
// Update is called once per frame
void Update()
{
float dist = Vector3.Distance(player.transform.position, maindoor.transform.position);
float radius = 5f;
if (dist <= radius && Input.GetKeyDown(KeyCode.F))
{
if (!IsOpen)
{
Debug.Log("F pressed in radius of the door");
opendoor.SetActive(true);
closeddoor.SetActive(false);
IsOpen = true;
}
else
{
opendoor.SetActive(false);
closeddoor.SetActive(true);
IsOpen = false;
}
}
}
}
probably told how to share, then ignored and did it wrong
use hastebin
this works too, it's pretty small
ive been sending scripts with this for a long time now
If they're too big, you should be using a paste site.
ye i use pastebin
You need to add logs into your if statements and see what's going on.
Nothing immediately jumps out as being wrong
perhaps the setup in the scene is
does it pull any errors
nope
i checked outputs
and i added prints too
didnt rlly get anything
wait i have an idea im gonna add a print(dist);
before the if statement
Debug.Log($"distance is: {dist}");
ye ima do that before the if statement
why the $ ?
whats the $ mean
to allow for putting vars directly into the string
ah i see
thats
very useful
ty
instead of doing Debug.Log("distance is: " + dist); which isn't efficient
is it really that different
it has a name, which escapes me atm
string interpolation? something like that
referencing?
one log? no.
thousands? Yes.
ok so @hexed terrace i think i figured out the error
ah true
this sounds right
yeah it's string interpolation, just checked
this ss doesnt say a lot
eh idk how to explain it
this is where my empty go is positioned
and when i go close to it
the dist is high
swap the vars
1- actually look at the console, not the single line at the bottom (click the console tab)
2- are you sure you've got the correct game object assigned? Not that it looks like there's a lot of things there that you could do incorrectly
so instead of Vector3.Distance (player, door) do Vector3.Distance (door, player)
ye im pretty sure, i even dragged it from hierarchy into the inspector (the script)
nah
i think if i just
put the closed door object
or open door object
instead of an empty game object
please write your sentences in one message, finish your sentences
mb im used to it
you can just click it to ping it, then you're not "pretty sure"..
ok so
i changed the vector3.distance to be the closed door (actual object) instead of the empty gameobject and it works
"Door" might be at some position far away.
While DoorOpen/ Closed were moved independently, giving them a different pos.
Having your pivot mode set to 'center' and selecting the "Door" gameobject will put the transform axis at the doors. Chaing to pivot (Z is the toggle hotkey) will show you were it really is
alr
for a single scene loaded, is there any Awake order guaranteed ? (for example from top to bottom hierarchy list)
u were right, its all the way over there
nope
is it random?
mh, i wonder what would a good approach when i have some "awake" dependencies between my objects
i dont really like the idea to have them query eachother and manually call some Init function
A manager script to load things in order.
OR
Use Awake to setup the class, getting references etc
Use Start to initialise the class with that data ^
Doing the Awake/ Start way is good practice regardless
the thing is this is an issue if i have Object 1, 2 and 3
and each ones needs to wait for the other to init itself before us
before us
?
for example
Object 1 inits in Awake
Objects 2 inits in Start (gets info from Object 1)
Object 3 needs Object 2 to init before it does anything, you cannot place it in Start because of inconsistent order
in this scenario the usual way is to have a bool isInited and a delegate onInitProcessed and have any dependent object use that on awake/start/whatever to know if it can run or not yet
Either the code needs refactoring with less dependency on each other.
Or use a manager script to enable things in order.
Or Object 2 has a reference to Object 3 and calls Init() when it's done.
könnte für manche sich wie das n word anhören
chill mal die wollen dir nur helfen
true
guys Im having an annoying problem where my characters spawn with crazy speed but I need to press on the prefab to apply the normal speed values in the game scene couldnt fix it at all
If this is a code problem then you share your !code properly inside #💻┃code-beginner
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 thing is Idk if its a code problem
here is a video of whats happening the problem is that I need to open the characters prefab to make them use the values I gave them otherwise the be so fast
hello
is there a way to make a wait in the update function
like a delay in update
you can run a coroutine or unitask and wait there
create one repeating coroutine then
you can also do this https://discussions.unity.com/t/fire-rate-issues/821482/2
No, that makes no sense
An update runs every frame, delaying it meaks you essentially block everything
You probably want to log a timestamp and simulate a delay that way by saving a variable Time.time and then check if the current Time.time exceeds this timestamp
Alternatively use a Coroutine combined with a boolean to indicate it runs, or some other way.
Context is important there so you should share what you actually want to do.
What's your specific situation that requires this? The situation will determine which other method suits you best
basically
ive made a simple door script
and i want it so
when the player clicks f in the proximity of the door (this is all in update)
the text that i have turns green then white again
after a short wait
Okay so timestamps in that case
If the player clicks, set a timestamp and update the text. If the timestamp ends, remove it again
See the example here on the documentation
cant i just do a different indicator
like an expanding circle
like when u click f it makes a text that makes a circle expand
maybe that
Alternatively just use a Coroutine https://docs.unity3d.com/6000.1/Documentation/Manual/coroutines.html
nah i re-decided im gonna make like a circle that expands when the player clicks f slowly
Coroutines are easier, but messier
Stuff like that is easily done with a lerp, which one again boils down to working with both timestamps and coroutines
ive heard of lerp from roblox lua but idk how to use it
Hi guys! It's been a day and I still haven't found a solution to this warning. The Gizmo isn't working in Play mode in Unity 6.1.
CommandBuffer: built-in render texture type 3 not found while executing (SetRenderTarget depth buffer)
think of it like a light switch. you turn the switch on, 3 seconds go by, the switch automatically turns off
in your case, when you click the door, set a bool to true and save the current Time.time, this is like you turning the light switch on
all the while the bool is true, you keep checking if the current time is more than 3 seconds than the saved time. this is like the light being kept on.
once 3 seconds is up, set the bool to false. the light switch is turned off.
then all you need is to do one thing when the bool is true, so setting the text color to green
when the bool is false, set the text color to white
Time.time is great
i took 5 seconds just input into google "CommandBuffer: built-in render texture type 3 not found while executing" ...-> https://discussions.unity.com/t/commandbuffer-temporary-render-texture-not-found-while-executing-setrendertarget-depth-buffer/870063
Once you get to using timestamps properly you can do a ton with them. Pretty much everything is possible with them where Coroutines can be more messy
Also, for multiplayer it's a lot better due to their small size in most cases
I found a the same thread yeah, but I'm not sure if it's the same bug.
You think this could be a problem specific to Unity 6.1?
In a fresh project, I don't see the same issue.
However, in my 3-day-old project, the problem started after I installed Cinemachine.
But even after uninstalling it, the warning still doesn't go away...
can there be problems about using a coroutine effectively like a stopwatch?
I mostly speak from a multiplayer standpoint and things like latency can mess up timing a lot here.
Say you lag for a second and your Coroutine is meant for 5 seconds, then it will still spend that 5 seconds on an action even though it might need to end after 4 at that point
Whereas if you have a synched timestamp, it will properly invoke on the remaining four seconds
This is pretty much unavoidable unless you agree on when it should stop, not how long it should last
Okay my bad, it happens in a fresh project too 😅
thats what ive wondered, but multiplayer isnt something ive had experience in
I would generally advice to use it as much as possible regardless for the consistency
the way they work still isnt that clear to me, they feel like they behave like youre making a thread because the way they execute doesnt exactly depend on the update loop
Timestamps?
It's a single variable
See the example on this page: https://docs.unity3d.com/ScriptReference/Time-time.html
I mean if an update frame happens to lag, the couroutine can keep running its process even if update hasnt finished yet
does anyone have some good tutorials for fps movement? preferably covering complexer stuff like dashing and sliding too. i found one but it was a bad tutorial and used a rigidbody and i would prefer a character controller
No, I mean that in the case of multiplayer latency can cause a Coroutine to start much later than intended
Vs a synchronized timestamp which is always ending at some point
It's not about lag DURING a Coroutine. Pretty sure that WaitForSecondsRealTime class or w/e fixes that
yeah, timestamps are what id always do for a stopwatch. coroutines are how I used to do it, and I think thats purely because you specifically tell them to wait X seconds
In most cases, anything involving a Coroutine or a timestamp relates to a visual feature. If not, it would be purely serverside anyway
So then you don't really worry about that
The best option is almost always to make it yourself so it can be tailored to your needs
i watched plenty of tutorials, i get how it works but i could write one myself just yet
also, why is gravity so bad?
its just way too strong, doesnt matter if i do anything to it
also, my groundcheck just deletes itself once i hit play?
Go to Project Settings > Physics > Settings > Shared > Gravity to adjust the base gravity
Gravity is gravity. Chances are you're doing something counter to how physics works that's making it not do what you expect
Because you have code that removes it
If you feel the need to adjust the base gravity, which is based on true gravity, you probably have your world scale completely off.
i didnt. after removing a different object from the player and placing it again, it just doesnt delete anymore? i also named it different
its the same world used in the presets for TPS and FPS presets
Objects don't just destroy themselves for no reason.
Perhaps you should actually show !code for context
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
instead of assuming fundamental forces of physics are broken
It's more likely that you're doing something that doesn't make physical sense like setting your Y velocity to 0 every frame
Snail, can you show us your code for the gravity problem
yeah one sec
I haven't used delegates and UI buttons in a while, so is there a reason this code keeps giving the same result for each button clicked instead of a unique result?
{
//Collect button components and assign handles to them
for (int i = 0; i < 4; i++)
{
GetComponentsInChildren<Button>()[i].onClick.AddListener(delegate { Display("Actor " + i); });
}
}
void Display(string name)
{
print(name);
}```
just experimenting a little more
Lambda Capture. It's basically the least intuitive problem you'll ever encounter. Basically, each of those delegates uses the same variable, instead of one created for that iteration of the loop, so each iteration is changing the i that the delegate uses.
Add in a line: int j = i before it, and use j inside the delegate and it'll fix it
Well, that did certainly fix it
To avoid getting stuck in tutorial hell would this be a good learning path to ensure I have the basics and a good foundation?
Unity Pathways -> CodeMonkey or GameDevTV -> Create Projects
Can you show the full !code for this script?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
@ashen arch @polar acorn
public class PlayerMovement : MonoBehaviour
{
public float speed = 12f;
public float gravity = -30f;
public float jumpHeight = 3f;
private CharacterController controller;
private Vector3 velocity;
private bool isGrounded;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
private void Start()
{
controller = GetComponent<CharacterController>();
}
private void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
velocity.y = -2f;
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
velocity.y = Mathf.Sqrt(jumpHeight * 2f * gravity);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void FixedUpdate()
{
}```
im not even sure what im doing anymore
A tool for sharing your source code with the world!
So, CharacterControllers don't even use gravity, you have to code it in yourself. And the issue you have here is that you're calling .Move twice. CharacterControllers should call Move exactly one time per frame. Never more, never less. You should do math on a single vector throughout Update and pass that one to Move at the end
oh
Here's what the full inspector looks like too
Well, there's two clips that are played off of the same audio source: mainEngineSFX and DashSFX. It could still be "playing" one and not doing the dash (even if it's just playing silence at the end of a clip, it's still considered "playing").
As a quick sanity check, replace that dash line with this:
AudioSource.PlayClipAtPoint(DashSFX, transform.position);
This will spawn a new AudioSource object at the location that destroys itself when the clip ends. It's more performance heavy than re-using one, so if this works we should still see about getting your existing audio source to work, but this can eliminate a bunch of other factors as the problem if it works.
It worked!
So the issue is the audio source itself. Try putting it back to how it was before, but putting audioSource.Stop(); before you play the dash sound
PlayOneShot shouldn't care if something's already playing, but it's worth trying to eliminate that as a possibility
Ok did that with ``` private System.Collections.IEnumerator PerformDash()
{
audioSource.Stop();
if (!audioSource.isPlaying)
{
audioSource.PlayOneShot(DashSFX);
}
Vector3 dashForce = transform.right * (dashDistance / dashDuration);
rb.AddForce(dashForce, ForceMode.VelocityChange);
yield return new WaitForSeconds(dashDuration);
isDashing = false;
// Cooldown before another dash
yield return new WaitForSeconds(dashCooldown);
canDash = true;
}```
Audio source isn't playing however despite some checks
Okay, so it's not that it's getting blocked. Does your thruster sound effect play properly?
yes the thruster/main engine plays properly
Ah, you know what, I just noticed something that I probably should have noticed immediately:
private void ProcessThrust()
{
if (thrust.IsPressed() && !isDashing)
{
StartThrusting();
}
else
{
StopThrusting();
}
}
You set isDashing to true immediately after hitting dash
The very next frame, this is going to call StopThrusting
which is going to call audioSource.Stop
Which, of course, wouldn't stop the spawned audio source from PlayClipAtPoint, which is why that one works
I see, let me try to set it to true a little later on and not immediately
my gravity is still broken, and so is jumping. now i also have the weird issue of overshooting when releasing W https://pastebin.com/5cbPbA3f
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
yo guys, any idea why this code doesnt work? (no errors, i tried to fix all of it already, the point is when u click e near the table it puts u on it)
using UnityEngine;
public class Pc : MonoBehaviour
{
public GameObject Player;
public GameObject Table;
bool isOnPc = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
float dist = Vector3.Distance(Player.transform.position, Table.transform.position);
float radius = 1.3f;
if (dist <= radius && Input.GetKey(KeyCode.E))
{
Debug.Log("E pressed near the table! Moving Player.");
Player.transform.position = Table.transform.position + new Vector3(0, 1, 0);
isOnPc = true;
}
}
}
what doesn't work.
well
it doesnt change
my position to the tables
or the tables and the vector 3
no errors, but theres also no debug.log printed
does your player use a CharacterController?
check the same things that caused the problem last time
like the whole E pressed part doesnt work
ah wait, no log printed means the condition is never true
look, i already have made a very similar script ( a door) and it worked just fine, so thats definetly not the issue
yea
but why
why don't you log useful information and find out?
i logged update to
or better yet use the debugger
Show the inspector of this object
and update worked fine
the objects are completely fine
i tied everything
how about you log something useful, such as the values you are checking
i logged dist in update
earlier
and it worked fine
prove it
bro what
Show the inspector of this object
in this class?
prove that the condition works fine now instead of just saying "trust me bro, i logged it earlier"
ok wait
and show the inspector as you've been requested multiple times now
Is your isGrounded firing when you expect it? Depending on your layer masks, it could be detecting something you don't expect, like the player itself or even a UI element. Try logging isGrounded and seeing if it turns true when you don't expect it
and is 1.7 bigger or smaller than 1.3?
i tried
going close too
dont worry
So the code's doing exactly what it should do
so PROVE THAT. why the fuck would you show a log that makes it clear that the condition is false when you are trying to prove that you are getting close enough to it
bro prove what
That distance isn't less than the value you set. So it doesn't run
i lit
went right up to the object
and i clicked e nothing happened
the distance was litteraly like
alright i'm out
And what number did it say for the distance
ill check
less then the radius for sure
like way less
So then
why did you show a screenshot
of it not being that
this is just more "trust me bro" instead of actual evidence
And expect us to just know that at some point it was okay
cuz he asked me to specifically print the distance
how to open animator window in unity i cant find the window tab to open it
this is a code channel. but also literally google it
Window -> Animation
Post this question, along with a screenshot of your entire Unity window, in #💻┃unity-talk
how do i log it? i tried setting it isGrounded to true again after being called but still not working, now i just get stuck in air. also collision is juts offset for some reason
Just log the value in Update and see if it's false when you expect it to be
Debug Log should literally have been the first line of Unity code you ever wrote.
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Debug.Log.html
ah
well pressing jump and the player sits still, isGrounded remains true and moving is impossible afterwards
to be fair though MonoBehaviour.print does call Debug.Log so you can use it, but Debug.Log has another overload to provide context to the log which is nice
are you sure you provided the correct code? the code you've shown does not do anything to prevent the player from moving ever, unless this component is being disabled from elsewhere
see that's the thing, it is not prevented from moving unless something is disabling a component. the code doesn't lie, so show the inspector for the object when this issue occurs
also, could it be related to the fact that the player spawns like this?i do not know how the collision just went underground. moving places you higher though, which means it shouldnt be clipping
nothing changes
and, to confirm, this is what you see while the issue is happening?
is the mesh and other collider a child of this object?
i swear man this was way easier in godot for some reason and i knew way less coding at that time
remove the collider from taht since the CC is already a collider, that one isn't necessary. and then set its Y position to 0 to match its parent. then adjust the object until it is actually above the ground
did that, now isGrounded is always false
make sure that is in the correct position now too. you probably had it in a location relative to where the mesh was rather than where the CC was so when you moved the CC (which was the root object) up, the groundChec object moved up too
no, don't do that. move the mesh to 0 on the Y axis
make sure everything is set up correctly rather than just moving the one thing then blindly trying to see if it works
issue persists :/
show the current setup and code
why am i gettin errors sometimes that doesnt have a source? how can i fix such errors ?
and preferably use a better site than pastebin, like one of the ones in the !code embed 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
this is an editor error. unless you've been writing editor code you can safely assume it is not related to your code
and how do i fix it ?
Use Scriptbin to share your code with others quickly and easily.
that's the neat part, you don't
make sure your tool handle is set to Pivot and select the groundChec object to make sure it is where you expect. then you can open up the physics debugger to see where your CheckSphere is and make sure it's what you expect
did you start by googling "unity physics debugger"
it seems like the collision inside is smaller?
i am really demotivated now
ive been stuck with trying to get walking and jumping work for the past 3 days at least
now you know why video games take years to make
godot was so much easier though
this feels like a unity problem, at least for me
great, then why not use godot?
because it runs really bad
and doesnt like writing and reading files
outside the .exe
sounds like it's not actually easier
Why not forget the jumping until you have your movement done?
the basic stuff was easier
the walking is broken too but i dont know why or how
are you using kinematic character controller?
just character controller, i presume its kinematic
alr
so, i'm switching my project's controls from input.getkeydown("") to unity's input action system. Altering my player's movement code was easy, but i've been struggling with the pause menu. I have the menu controller in the ui panel itself, and no matter what i try, the game doesnt bring up the menu even with the keys configured. i'm not sure if i'm missing something obvious or what, any tips are welcome!
You might need to enable the action in order to receive input for it. In the code that works, do you have an action.Enable() anywhere?
i don't remember writing one, i'm guessing that needs to be in the player controller?
here's my movement control script:
Also I haven't seen this way of retrieving the action, you'd either refer to the C# class generated by the Asset, or by using an input event component (whatever it's called) to forward events
Yeah here like in this second script
You have the OnXXX(CallbackContext ctx) methods
I generally don't use the input actions that way.
You could try using InputActionReference instead of InputAction
Then in your script you need to yourRef.action.performed += SomeMethod as long as SomeMethod takes an InputAction.CallbackContext parameter.
That will trigger SomeMethod every time the input is performed
-= will remove the method from the action, when you don't want the method listening for the input anymore
By using InputActionReference you won't need to find it, you can just select it from the inspector
i guess the documentation tripped me up, i was looking at the action workflow
There's a number of different ways to use the new input system, so at first the documentation will trip you up
where do i put in the stuff the package i got from the asset store contains? cant find it
i already downloaded it
through the package manager?
it should be somewhere in your packages folder
when you import a package it'll have a filetree preview that you have to confirm..
it'll tell you there where its going (folders/subfolders) if there's no folders it'll go str8 to the main root asset folder..
if its plugins and/or stuff like that parts will be in those folders
ah
decent packages will also have demo scenes with most things set up or there in teh scene.. and readme's documentation
I have a projectile with a (1-2 seconds short) lifespan before it destroys itself. Is there any major functional or efficiency difference between using deltaTime or a Coroutine to go about that?
{
//movement stuff
timeElapsed += Time.deltaTime;
if (timeElapsed >= lifetime)
{
Destroy(gameObject);
}
}```
Or
{
yield return new WaitForSeconds(lifetime);
}```
If I start the Coroutine in Start(), is there any practical difference between the two ways?
if by practical you mean visually.. or the result then no..
the coroutine doesn't rely on Update() soo it reduces unnecessary per-frame checks.. biggest difference imo
if its a set-it and forget-it moment i'd say use the coroutine
Alright, thanks^^
its not free it still is "checked" each update by unity
Do use coroutines.
What am I even doing wrong here?
Nothing wrong. Looks good to me.
I would actually use update here. Im not so sure why others are saying coroutines. The only time id avoid update here would be if the object was just laying around waiting to be "started". Because in that case, you would have to use a guard clause in update to return early, basically checking if it should run or not. You wouldnt have to do that in a coroutine, because it'd only be running when you tell it to. This doesn't seem to be the case for you
it's also a micro optimization but starting a coroutine allocates memory. I see no reason to use one here. A coroutine still does check the condition every frame as rob said
Clearly not, cause when I jump works fine, when I jump AND move now it's broken
It's also easier to implement any functionality around it, such as pausing the game.
void Update()
{
if (Game.instance.paused) {
return;
}
//movement stuff
timeElapsed += Time.deltaTime;
if (timeElapsed >= lifetime)
{
Destroy(gameObject);
}
}
That's the princess jump from super mario bros 2. Kinda cool.
Indeed, I was going for a normal one though... So not cool
look at the #854851968446365696 on what to include when asking questions. No one wants to play 20 questions to ask you whats wrong, and then ask you for the code, and ask if you debugged, and ask if you know which line is specifically going wrong.
Can you show your code?
when ur setting the vector for ur lateral movement ur probably setting the Y to 0
Sure, give me a sec
and not letting the gravity do its job
need to pass in the velocity it already has along w/ ur movement for the other axis
Try to show us maximum of 10 lines of code. Trim it down if possible for the question here.
ur over-writing ur gravity/
Jump script or movement script?
Ah, I see...
yup, its a common issue.. no code needed lol
new Vector3(inputX, controller.velocity.y, inputZ);
or w/e combination u need to use
I think I understand the problem now
bawsi, can you click on the muscle reaction please
followed your advice and restructured my code into a callback context method, but it seems to just skip the menuCanvas.SetActive line and skip to pausing the scene? idk whats going on, even after f-ing around with the program with pretty much anything i can try
it successfully prints out the Debug.log, which makes the whole sitch even weirder
wait lol nvm, just fixed it
What I asked doesn't break any of those rules...? And I got the answer I needed without causing trouble so I don't see the issue here
They were directing you to this section
I'm aware, I wasn't looking for something specific though so to be brief I posted what I did
is it possible to mark the triangles used by an agent and add extra cost to them? from what I can tell it is impossible to directly reference navmesh triangles, as well as impossible to set an additional weight modifier on top of a triangle's default area cost...
i didnt say u broke a rule. im directing you to it so you can get help more efficiently. people will eventually skip over questions if they can't be bothered to pry information from you. Notice how for the first message you got in response, you had to clarify that "when I jump AND move now it's broken". This is information we want from the start
Maybe someone else can correct me if its possible but I dont think it is. you might have to use the navmesh areas and set a different area type
wouldn't that override the area type that was set on it previously?
I would still need some way to get a list of all the triangles an agent is using for its path as well
I saw that there was "get triangulation" or something, but it doesnt really tell you how those verticies are organized so im not sure how I would get the triangles from that
is there something u need the actual triangles for? i would imagine this is either an XY problem or not a beginner problem at all.
I was thinking something like this for setting the area cost https://docs.unity3d.com/6000.1/Documentation/ScriptReference/AI.NavMeshAgent.SetAreaCost.html
the NavMeshPath just has the corners
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/AI.NavMeshAgent-path.html
I can't be bothered to figure out what the unity discord considers a "beginner problem or non beginner problem." no matter where I post I get yelled at.
As for why I need the triangles (or polygons, if they aren't all triangles) is because I'm trying to make enemy AI take multiple routes to the player, via the method of increasing the cost of certain nodes that have already been taken recently. If I do it based on nodes though, which would be the vertices of the triangles, then each hallway now has two logical paths, right? one on each edge?
setting the area cost from what I read changes the cost of ALL polygons in that "area" tag, like a layer
whereas I need to set the cost of individual paths, not entire types of terrain
no ones yelling at you for it. Im just saying that getting the triangles would imply you might be doing something complicated unknowingly.
This isn't something ive done myself so you might need to test it out, but the method I linked you is on the navmesh agent, NavMeshAgent.SetAreaCost, so I would assume this is specific to the agent itself.
it is, but from how I read it, it sets the cost for an area type
I have a picture of what im trying to do one sec
Should I be using SerializeField when possible in unity? Or is it better to do a getcomponent call when both are possible? What is good practice here
serializefield means you would be directly referencing the component you want. this is better always when you can do it
Okay, thank you
say the enemy takes this path, I want it to add a cost to all these sectors so that the other enemies will avoid that path, and naturally take the flank routes
Hey! I need to save the float of 'music' on myMixer to a variable just wondering the best way to do this in c#
When I unpause I need it to return to the same value so I need to take note of it before setting it to 0
Assigning variables uses one =
Not two
== is for checking if two things are equal
Oh yeah whoops
So I have
public float savecurrentvolume;
savecurrentvolume = myMixer.GetFloat("music");
But i'm ghetting this on 'getfloat'
That can only return a bool?
I'm lost
Ah I see what you mean. Yea unfortunately haven't done this myself but I would assume the easiest way here would be with navmesh modifier volume to affect the area type for future agents.
if(myMixer.GetFloat("music", out float musicVal))...
out variables exist to get data out via an argument
hm, I feel that would be inefficient and prone to potential unintentional overlaps unfortunately, making a bunch of entities. I was planning on making a hashmap of triangles to booleans and clear it every 4 seconds or something like that
is there really no way to just increase the cost of a node in the underlying pathfinding calculation?
I'm still confused, I just need to save the current value of it to 'savecurrentvolume' float
Then you would pass that as the out parameter
float myCoolVar = 1f;
myMixer.GetFloat("music", out myCoolVar);
many ways to use out!
Oh! That's neat
the point of the function returning bool is so you can check easier if it was successful or not
the cost is just seemingly associated to areas only. Yea this would most likely require your own pathfinding then on top of unitys navmesh
@high summit
if(myMixer.GetFloat("music", out float musicVal))
{
//Do stuff
}
else Debug.LogError("music was not found in myMixer!");
I think it'd realistically be fine to just place volume modifiers around with a higher area cost, but you'd want to control when paths are calculated so you can also associate the agent the volume modifiers placed down
Thanks guys, all working, I need to somehow mute through code but according to the tinterwebs, it's not possible?
Why is my cube really really slow?
I could try, im just worried about performance, especially since it's creating a bunch of entities, and I don't know how to measure that performance impact exactly. but maybe as a temporary measure. I like the idea of custom pathfinding, though that will take a while to learn how to do. Plus, can I even do custom pathfinding on the unity navmesh if I can't access its polygons?
can anyone help please?
Brains having a hard time trying to figure out a solution to this.
Once you hit pause.
It saves the current mixer volume, and sets it to -100 (essentially muting it)
myMixer.GetFloat("music", out savecurrentvolume);
myMixer.SetFloat("music", -100);
Then when you unpause, It sets it to whatever the saved value is, (so it's back to the save volume)
but if i move the volume slider in the settings, it obviously unmuted because it's moving it out of the -100 state, But this means volume comes back in the pause menu.
After some googling, Unity lets you mute the mixer in the editor, but this functionality is not exposed to code so it cannot be done via code (which would fix my issue)
Anyone got any ideas how I can work around this?
(vs muting every single audiosource during pausing)
Thanks!
Just dont write back the volume strait away?? When you un pause you can restore volume using the new saved value
And my code is not respecting physic laws 😭
oooh that's not a bad idea
okay so this is the slide script
[SerializeField] private AudioMixer myMixer;
[SerializeField] private Slider musicSlider;
public void SetMusicVolume()
{
float volume = musicSlider.value;
myMixer.SetFloat("music", Mathf.Log10(volume)*20);
}
I need to save the float volume so it can be used in the other script that unpauses
Do you store user settings anywhere like in a file?
I do not, It's a one time play game without saves
Then just have some static field somewhere you can read from/write to, e.g:
public class PauseMenu : MonoBehaviour
{
public static float MusicVolume;
}
Probably easiest for you if your current design is messy
well if you have a new script per slider just slap it in there
Nice, In slider I have
public static float MusicVolume;
float volume = musicSlider.value;
MusicVolume = Mathf.Log10(volume) * 20;
And then in unpause logic I have
myMixer.SetFloat("music", VolumeSettings.MusicVolume);
And thanks worked perfect, thanks for the help rob
What makes something static? It's a changing value so I find the wording confusing
means it no longer belongs to instances of a class but to the class name (a.k.a 1 global value)
static means it belongs to the class itself, not any specific instance of it
snap
Yea sorry this is something I've never done in unity at so dont know what to say there. Pathfinding algorithms arent that complex, all the implementations are available online. I just dont know what data youd use from navmesh and am not on my pc to check. Maybe this is something to ask as a separate question, or a question along the lines of getting agents to take different paths to the same destination.
dont modifier volumes subdivide the mesh too?
but yeah ill try it and see
I do think its weird you cant just get a list of individual sectors though
Hey! So i want my scene to start with a black screen then fade into the actual scene. is the best way to do this just putting a black 'image' on a canvas covering everything and then fade it's alpha value with code?
Or is there a much easier way im missing
Basically trying to do this
video player wont give me the option to assign an audio source 😿
(the object sits on a prefab)
!publisher
✒️ If you're an Asset Store publisher looking to apply for that role, please DM <@&502880774467354641> with an image of your publisher dashboard to be added. It may take a week or so to get to your request, please be patient.
nvm had to drag in a video
(P.S. it works even when you clear the video slot)
i just need a quick sanity check. is it not a normal thing for devs to always have the error list open in visual studios? i've been watching some unity devs on twitch and there's a weird amount of them who never even open the error list
Ideally, it's always empty
oh yeah, true lol
Just press the shortcut that cycles through errors and look at them directly
yes that's a very easy/common way
Is there a better way to do this? I want to do a dictionary for strings to Tiles in the inspector, but dictionary isn't serializable
i feel like this should be an FAQ, i see this question soooo often.. just worded a bit differently.. or just a slightly different situation.. idk tho
this is pretty common
there's some packages that give you a SerializableDictionary, but those packages all do something similar to this under the hood
o ok cool thx
Cant seem to drag my canvas group in here following a tutorial on fading out a canvas
Maybe i'm getting canvas and canvas group mixed up
do you have an object that has a CanvasGroup component on it?
That was the isssue, I thought I canvas group was just a canvas grouping stuff inside it lol
thanks
Is it possible to have two scenes running and have the fixed delta time in each scene different?
I don't think so, but you could achieve that by ticking the PhysicsScenes yourself
I have this gravity code running in a fixed update:
{
//apply each gravity wells gravity to each orbiting object
foreach (var orbiter in orbiters)
{
orbiter.rigidbody.AddForce(GetGravity(orbiter.rigidbody, gravityWells));
}
}
public static Vector3 GetGravity(Orbiter orbiter, List<GravityWell> gravityWells)
{
Vector3 result = new Vector3();
foreach (var gravityWell in gravityWells)
{
//check to see if object is not itself, maybe not needed, maybe planets are on rails? could cause n-body hell
if (!gravityWell.gameObject.Equals(orbiter.gameObject))
{
// Newton's law: F = G * ( (m1 * m2) / r^2 )
float m1 = orbiter.rigidbody.mass;
float m2 = gravityWell.rigidbody.mass;
float r = Vector3.Distance(orbiter.transform.position, gravityWell.transform.position);
float gravity = gravitationalConstant * ((m1 * m2) / (r * r));
Vector3 normalizedDirection = (gravityWell.transform.position - orbiter.transform.position).normalized;
result += normalizedDirection * gravity;
}
}
return result;
}```
I was hoping to have a scene in the background running faster to plot the trajectory lines, because the math to do so myself seems quite gruesome.
So I would just run the scene like ten times faster and then pause it once I plotted the lines, based on the alternate scene version of each rigidbody.
I'm guessing it just wont work now though.
My concern / question would be if my code above in a FixedUpdate would be affected by the PhysicsScene settings.
or only the built in physics
In this case you could just tick the simulation a bunch instead of changing settings
Hello, I'm trying to understand a good way to make context based user input. Right now, I'm trying to make it so that when the mouse clicks, it invokes an event callback, and so everything subscribed to it will check if the context fits (ui checks if the click is on a ui, tilemap checks context if the player is in a state that allows them to interact with the clicked location, etc). I don't think this will work, since I can't control the order of invocation easily. Should I be handling the context/state checks in the input manager class instead?
I tried to tick the simulation ahead and the gravity equation in the fixed update is not being counted at all.
hi
if you have a unity question just !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
O damn srry
I dont think PhysicsScene.Simulate calls FixedUpdate on the script components in that scene
So you'd have to call your gravity method manually
Hey everyone, I’m running into an issue with GUI.DragWindow() not allowing my window to be dragged, despite being included in my WindowFunction. My implementation involves scroll views inside the window, and I suspect they might be interfering.
Here’s a simplified version of my setup
private Vector2 LeftScrollArea = Vector2.zero;
private Vector2 RightScrollArea = Vector2.zero;
private Rect windowRect = new Rect(100,500,760,450);
void OnGUI() {
GUI.Window(windowID, windowRect, WindowFunction, $"Bot Settings {windowID}");
}
void WindowFunction(int windowID) {
LeftScrollArea = GUI.BeginScrollView(new Rect(10, 20, 225, 400), LeftScrollArea, new Rect(0, 0, 150, 600));
GUI.EndScrollView();
RightScrollArea = GUI.BeginScrollView(new Rect(240, 330, 510, 100), RightScrollArea, new Rect(0, 0, 150, 300));
GUI.EndScrollView();
GUI.Box(new Rect(250, 25, 500, 300), "Waypoints");
GUI.DragWindow();
}```The issue: The window remains static and doesn’t respond to dragging. I’m wondering if the scroll views are intercepting mouse input, preventing GUI.DragWindow() from registering correctly.
Has anyone encountered a similar problem? Could it be due to the order in which elements are drawn, or do I need to explicitly handle event propagation? Any insights would be appreciated!
arent you missing size for drag area for DragWindow or am I missing something? I barely am familiar with it
GUI.DragWindow() doesn’t require an explicit size for a drag area, afaik
you can try windowRect = GUI.Window(windowID, windowRect, WindowFunction, $"Bot Settings {windowID}");
Is it possible to apply timescale = 0 for all objects except the player
no, timescale is universal, it just affects deltaTime/time
what you can do instead is use unscaledDeltaTime/unscaledTime on the player specifically, that'd make it not respond to any timeScale changes
or if you need finer control, you'll have to control that yourself
Thanks
I'm currently thinking of a velocity multiplier to pair with a singleton that dictates my timestop boolean, do you think that will be better?
is there a rmb version of OnMouseUpAsButton?
rmb ?
right mouse button
dont think so but you could probably just achieve the same thing with Input GetMouseButtonUp(1) + a raycast?
IEnumerator RightClickPlayer()
{
if(Input.GetMouseButtonUp(1))
{
Debug.Log("functioned");
StopCoroutine(RightClickPlayer());
}
yield return null;
}
private void OnMouseEnter()
{
StartCoroutine(RightClickPlayer());
}
spaghetti coding rn
if you gonna use a coroutine for that you'd probably want to use WaitUntil()=> Input.GetMouseButtonUp(1)
yield return WaitUntil(() => Input.GetMouseButtonUp(1));
missing extra ()
did i use it incorrectly or do i need to update
myb
thanks
yield return new WaitUntil( ()=> Input.GetMouseButtonUp(1) )
this is basically just calling that function every frame anyway, you can easily use a while loop or update as well
there are slight garbage implications of new() a new object each time
quick question, how does the new keyword allow me to use WaitUntil as a method?
WaitUntil is a Yield instruction, basically another coroutine
so you create a new object that is the instruction that waits an event, this case evaluates a delegate until true
Thats very helpful to know, thanks
(on the other hand this isnt working for some reason so i guess its time to learn raycasting XD)
what did you write exactly, also it should work but probably not what you expect
and did you test it with a Log prior to the yield?
yes to this but turns out I forgot to remove the if statement earlier XD
You're calling the constructor for the type when you use new. It's a method that creates an object
OnMouseEnter could be an issue to start coroutine if you enter another collider if you haven't released mouse 1 it will be 2 coroutines running
or whatever amount of times you enter collider without release mouse1, you need to place some other checks most likely
so what you're saying is that I should add a fallback that detects if the player leaves the collider?
also its not detecting right clicks for some reason
idk exactly what you need to do
I'd probably use OnPointerUp (you need physics raycaster on camera) and go from there
so maybe.. something like cs public void OnPointerUp(PointerEventData eventData) { if (eventData.button == 1) { Debug.Log("Right mouse button released"); }
only quirk is this code goes directly on the collider, the upside is you know it only run on a specific collider
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IPointerUpHandler.html
Note: In order to receive OnPointerUp callbacks, you must also implement the EventSystems.IPointerDownHandler|IPointerDownHandler interface 🙄
btw not sure if you still have that issue but I tried #💻┃code-beginner message myself and it did work fine
turns out it wasnt detecting right clicks because i was also using the same collider to detect for left clicks, didn't know that it was mutually exclusive
Have you done a file selector? Like the Zelda NES one where you can choose the file (you have created), make a new one or erase. I want to do that with my game. 3 files to load, create or erase.
Time to learn json
All right then
https://docs.unity3d.com/6000.0/Documentation/Manual/json-serialization.html
https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Application-persistentDataPath.html
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=net-9.0
something to give you an idea on whats involved
is it better to use a public static variable or a singleton for a global boolean?
or a scriptable object
Didn't you go through that yesterday already? The answers haven't changed since then
just tried using timescale 0
failed horribly
tried singleton
wasn't able to get it working
That doesn't seem to be related to what you asked first. If you're having problems with code then show it and explain the issue
originally I simply tried using a system that changes timescale to 0 on key down, this obviously failed
Yeah that has nothing to do with global variables
If you're trying to make something like a time freeze feature in the game you'll have to design for that from the ground up, it's not something you can do by just adding one variable
I always have a gameobject called Game with a script of Game.cs that I use for some global stuff, e.g. bool paused
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.InputSystem;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
[DefaultExecutionOrder(-5)]
class Game : MonoBehaviour {
public static Game instance = null;
public bool paused = false;
void Awake() {
if (instance == null) {
instance = this;
DontDestroyOnLoad(gameObject);
load();
init();
}
else {
Destroy(gameObject);
}
}
}
// ... other code here
void load() { /* load saved data*/ }
void init() { /* init some stuff*/ }
// Player.cs:
void Update() {
if (Game.instance.paused) {
return;
}
// other code
}
that's similar to what I did
I'm still trying out implementing it
I'm struggling to link this to the player script tho
since I need to get key down from my character controller
If it's static, and in your scene, you should be able to access it from any script, like I did in the example "Player.cs" part (above) at the bottom.
Yeah, I have other code in my Game.cs, like:
[Header("Input Control")]
public bool allowInput = true;
public bool isMoving = false;
public bool isMovingDown = false;
public bool isMovingDownward = false;
public bool isMovingUp = false;
public bool isMovingUpward = false;
public bool isMovingRight = false;
public bool isMovingRightward = false;
public bool isMovingLeft = false;
public bool isMovingLeftward = false;
public bool isAttacking = false;
public bool isJumping = false;
public bool isCrouching = false;
public bool isInteracting = false;
public bool isStarting = false;
public bool isLeftTriggering = false;
public bool isRightTriggering = false;
can you modify the value of the static bool from the player?
when you call it
Yeah, just do Game.instance.paused = true; from any script, in my case.
or is it private set?
instance is public static. and the paused bool is public.
so the script is both public get and set
ah
ok thanks I'll need some time to get it going
Okay
The pattern is called a Singleton, and you should generally use a property to declare the Instance variable so no outside script can set it
when I call a method in the class is it just game.instance.methodname(kwargs)?
Yes
Though Game would be a class, which should be capitalized (Pascal case), as should method names (and even public members if you're following the C# standards, which differ from the Unity built-in members)
Yeah, remember to put the Game.cs script onto an object in your scene (Hierarchy). I personally just create an empty object called "Game" in my scene and put the script on it.
I currently have this: public void timestopStatus(bool _requestedTimestop)
now, I'm trying to access the code from my character controller which has Timestop = input.Timestop.WasPressedThisFrame() ? TimestopInput.Toggle : TimestopInput.None linked to the code _requestedTimestop = input.Timestop switch { TimestopInput.Toggle => !_requestedTimestop, TimestopInput.None => _requestedTimestop, _ => _requestedTimestop };, so when I do pass my requested timestop and call the function into the singleton, supposingly it should be able to listen to the keydown event
that's my logic, at least
I dunno, I can't really read your code. I don't use arrow functions, and never seen switch keyword placed like that.
it was some recycled code from a tutorial and that's like the only way i know how to do a toggle lol
If I instantiate an object that automatically becomes a listener of an event, does that object remain within the list of listeners of the action if it's destroyed?
if you want to toggle a bool, just do myBool = !myBool;
The reference to it (the object) will still exist. Any object subscribed to an event must unsubscribe when it is destroyed . . .
destroying an object doesnt remove it from lists or anything really
Mmmm, then I should probably be unsubscribing my buttons when they are destroyed...
in some cases it doesnt matter but yea its generally a good practice to always do. especially if you dont know when you should be doing it
I was actually thinking how I would manage to do like a "cheat death system". Like when hp reaches 0 first send a call to see if there are any "deathcheats" that can trigger and if not, proceed normally
Yes, not removing listeners can lead to memory leaks . . .
And I was thinking if it might be a good idea to check if the list of listeners was empty to manage that
it sounds odd that you would specifically be checking if a delegate was empty to decide if the character is dead. It might end up being pretty limiting too though im not sure how you designed the game here. Like lets say before death, your character has some way to cheat death, but only if some condition is true. You would probably want to use the return value of this cheat death method to get a true or false response about if it should still be alive. The method thats subscribed to your event could be handling the actual logic of giving the player more hp
Yeah, I would want to have different conditions to check if the CheatDeath is triggereable, but mainly this would be on coldowns so suscribing on Awake, unsuscribe on trigger and suscribe again on a timer may work just fine
Mainly is limiting for stuff like "I only want this to trigger if the overkill was less than X" for example
So I am not sure how I would do that in particular without making a mess of code
How could I return a bool on event for example?
unsubscribing and subscribing constantly sounds a bit messy imo though it can definitely work. the only real issue i see here, in either case, would be if you wanted to prioritize certain ways of cheating death. you dont really have any control to the ordering here
returning values from delegates is a little more tricky in that you should probably process the values manually. You might want to look at proper resources online about it and experiment in some online compiler just to learn it quickly
I mean, they would be on order of suscriptuon by default, but I don't really care much of the order anyways
{
_requestedTimestop = !_requestedTimestop;
if (_requestedTimestop && timestopSeconds > 0)
{
Game.instance.UpdateTimestopStatus(_requestedTimestop);
timestopSeconds -= Time.deltaTime;
}
}
// on Game.cs:
public void UpdateTimestopStatus(bool _requestedTimestop)
{
timestopTriggered = _requestedTimestop;
}``` is this a correct implementation?
Worse case scenario I could make like different tiers of priority at which these are called
Like CheatDeath1 to 3 and call them in order
If you have two _requestedTimestop properties, 1) in that script, and 2) in the Game.cs, then it looks correct.
yes, the second one within the UpdateTimestopStatus(bool _requestedTimestop) is just the kwarg
https://dotnetfiddle.net/4FSXK4
this is what I mean by the way when I say its a little more tricky. This isnt something i commonly do, but you'd probably want to go through the GetInvocationList. I don't really know if theres a better way here since i dont know much about your game. If you can somehow avoid this and manually declare how these are processed it might honestly be easier.
Okay, but you're only updating the one in Game.cs when it's true. If that's intentional, okay.
thanks, it is intentional because I only wanted to update the call when I know there's a valid request
then if it's always true, then Game.instance.UpdateTimestopStatus(_requestedTimestop); is the same as writing Game.instance.UpdateTimestopStatus(true); on that line.
Is there really much of a difference from getting the list of listeners from like accesing any other list?
how would I turn it off then?
by a toggle in my script
{
_requestedTimestop = !_requestedTimestop;
if (_requestedTimestop && timestopSeconds > 0)
{
Game.instance.UpdateTimestopStatus(_requestedTimestop);
timestopSeconds -= Time.deltaTime;
}
else
{
_requestedTimestop = false;
Game.instance.UpdateTimestopStatus(_requestedTimestop);
}
}```
this is what I've made pretty quickly
Just move the Game.instance.Update line to be after _requestedTimestop = !_requestedTimestop; line
so likeif (input.Timestop) { if (_requestedTimestop && timestopSeconds > 0) { Game.instance.UpdateTimestopStatus(_requestedTimestop); timestopSeconds -= Time.deltaTime; } _requestedTimestop = !_requestedTimestop; }?
I don't know what you're trying to do. You either want:
if (input.Timestop)
{
_requestedTimestop = !_requestedTimestop;
if (_requestedTimestop && timestopSeconds > 0)
{
Game.instance.UpdateTimestopStatus(true);
timestopSeconds -= Time.deltaTime;
}
else
{
Game.instance.UpdateTimestopStatus(false);
}
}
or
if (input.Timestop)
{
_requestedTimestop = !_requestedTimestop;
Game.instance.UpdateTimestopStatus(_requestedTimestop);
if (_requestedTimestop && timestopSeconds > 0)
{
timestopSeconds -= Time.deltaTime;
}
}
oops, edited.
the second one I guess, looks a bit cleaner
accessing it is quite literally just through the GetInvocationList and then invoking the methods yourself
essentially just a toggle for the system, and pass the toggle when it's true and have timestopSeconds
otherwise it's false
it depends, because you have an additional condition there of timestopSeconds > 0 which I don't know about, and therefore both examples I provided are technically different, not just in cleanliness/readability.
timestopSeconds just counts how much time you have paused because you cannot stop forever
In that case I think method 1 is better
I can't say. you'll have to test it, and see how and why you're setting/getting/accessing on the bool from Game.instance.
yea, I'm gonna mess around in the editor for a bit and see if it's working as intended
https://dotnetfiddle.net/Y3IdDI
replace int with bool and this is pretty much what I meant. It's up to you if you want to unsubscribe/subscribe when it's actually valid to cheat death, or just use a return value and check if the value is true. I think either way, you might* need to process this manually. For example if 2 ways of cheating death are currently valid, and you just invoke the delegate, it will go through both methods (possibly putting them on cooldown or whatever side effect exists). This would feel like shit to the user if they had 2 methods for surviving and both get used after dying once
also i vaguely recall something something about boxing values in the example i wrote, but im not smart enough to know much about that. I'd assume the alternative of constantly subscribing/unsubscribing would be worse in terms of allocations. Just bringing it up incase you somehow want to research more into this
The idea would be to check the invocation list to see if it's an empty and if not call just the first one
Not sure if can do that, so I may just create a manual list of deathcheats and basically call their "OnCheatDeath" method manually
I think I'm missing something
Yea that's what I meant by processing it manually.
This would also let you control the order, so up to you. I think any of the solutions would be valid
Null references errors are the same always (unless it's a unity editor bug). Something is null and you're trying to access a field or method on it
doesn't look like I'm missing something
A tool for sharing your source code with the world!
I'm pretty sure I set up the singleton correctly
You might be trying to access Game.cs too early. Try adding [DefaultExecutionOrder(-5)] above public class Game : MonoBehaviour
does awake on script have sequences to when it is executed? if so, how can I check it?
Yes, so, that [DefaultExecutionOrder] can tell a script to load earlier. I don't know how to check the current order.
it is still coming up empty
You'll need to show me what line 168 and 174 are.
Are you trying to access the Singleton using an Awake method in another script?
Nope, just a update method
Also, you need to show us the code from the error lines . . .
Look for any reference variables on those lines and check (test) if they are null . . .
the system is under UpdateInput which is under Update in the player script, so there should be no problems there
Game.Instance.UpdateTimestopStatus(_requestedTimestop); has a null pointer
[DefaultExecutionOrder(-5)]
public class Game : MonoBehaviour
{
//initialise singleton
public static Game Instance;
void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(this);
}
else
{
Instance = this;
}
}
// handling global variables
public bool timestopTriggered = false;
public void UpdateTimestopStatus(bool _requestedTimestop)
{
timestopTriggered = _requestedTimestop;
Debug.Log(_requestedTimestop);
Debug.Log(timestopTriggered);
}
}
``` should be working fine, no?
Yeah, and you have an object in your hierarchy/scene with the Game.cs script on it?
I would just create an empty object in your scene called Game
ah so when the player is destoryed it wouldn't affect the code
(A lot of people call it a GameManager)
yeah
Yeah, I used to use GameManager naming. then i decided to call it Game
Hey guys, why is my character controller ignoring the max slope value? Like when a slope is inclined at more than 45° and my character controller max slope value is 40, the player can still go up the slope
Im on unity 6.1 2f
Can't believe I made such a stpid mistake lol
Yeah, I even said to you "Remember to ..." lol

is there some code that we can read and see the logic?
Worked fine in other project btw (projects made in unity 5) but i havent checked if it is a unity 6 bug or no
there's a possibility that some stuff was changed
Right now i dont have access to the code but it just gets the horinzontal input * transform.right and vertical input * transform.forward
Then i call the move function
Hope not cuz i made a capsule check for is grounded but the problem is that the player can jump on slope do I was gonnamake a slide functuon with the slope normal but it doesnt matter if the character controller max slope doesnt work
Rn cant talk im in school
hmmm I'm still a bit confused as to how this will relate to max slope
Cuz then the player can stil climb up
A slope
So maybe ill just make an alternative idk
Like myself prevent the player from moving
But if there is a fix ill tzlke it cuz eqsier
my understanding is that you could dot product divided by magnitude to get an angle
and if said angle is larger than 45 degrees (pi/4 radians) you detect and tell the player not to go up any further
I'm not sure how your system is implemented but I use kinematic character motor and the way I do it is this:
if (motor.GroundingStatus.FoundAnyGround)
{
// check to see if player is in same direction as the resultant velocity
if (Vector3.Dot(movementForce, currentVelocity + movementForce) > 0f)
{
// get the normal of the obstruction
var obstructionNormal = Vector3.Cross
(
motor.CharacterUp,
Vector3.Cross
(
motor.CharacterUp,
motor.GroundingStatus.GroundNormal
)
).normalized;
// prevent movement force that would boost the player
movementForce = Vector3.ProjectOnPlane(movementForce, obstructionNormal);
}
}
currentVelocity += movementForce;```
this is under the assuption that you are not on stable ground (dictated by my kinematic motor)
Typically, you'd place this on a separate GameObject as it is not related to the Player . . .
yea, I did, I felt stupid for forgetting
my toggle is fine now... but for some reason if (GameManager.Instance.timestopTriggered) { timestopSeconds -= Time.deltaTime; } is not ticking down correctly
is timestopTriggered called once, or every frame
could someone help me w VR? please dm me:))
You won't get any DM help here
Just ask what you need here
I know how to get it, but i just wanna know how i can fix the character controller max slope not working issue
Also cant i just get the angle with Vector3.Angle(hit.normal, Vector3.up)?
It wouldn't give you a reflex angle nor give you a negative angle
Also I'm not sure how it dictates the rotational angle
How can you load a specific sprite from a sheet into an UI.Image given you have the name of that sprite (not it's index)?
frontImage.sprite = Resources.Load<Sprite>("Assets/Visuals/Cards.png");
^ this doesn't seem to account for spritesheets
Sprite[] sprites = Resources.LoadAll<Sprite>("Assets/Visuals/Cards.png");
^ and this doesn't seem to retrieve my sprites at all
Neither of those should load anything at all. Check https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Resources.Load.html for what the path should be
Ok, so I moved my spritesheet to the Ressources folder and fixed my path. Now what?
test?
I still don't get how to access one sprite from a sheet using Load()
Didn't work
oh wait, I'm supposed to remove the extension too my bad
It worked
Why does the extension break it? what if there are two files with the same name and a different extension?
then it won't work
unless they're different types, it probably can differentiate them in that case
Is there a way to retrieve one of those sprites by name from that array instead of by index?
Oh ok
But about the character controller max slope not working, do u know a fix or why it isnt working properly?
Not sure if this is any help, but you can filter the collisions by their normal angle with a ContactFilter, like explained in this forum post :
https://discussions.unity.com/t/best-ground-detection-method/897715/2
It can be used to distinguish ground, slopes, ceilings, etc.
it's not recomended, what are you trying to do here?
I figured...
I have an UI.Image and want to change it's displayed sprite given that I know the name of the sprite in the spritesheet.
Ideally you wanna avoid hardcoding stuff in strings like that.
What is the logical reason that makes you want to switch the sprite reference in this context?
Oh ok
The function should take, for example "1D" as a string parameter and update the UI.Image to the sprite I named 1D.
yes but why
Does it work for 3d too?
I assume, but it's not ContactFilter2D in that case
Aren't UI.Images supposed to support changing their sprite at runtime?
Yes, I'm not saying you can't I'm just trying to work through the solution with you
you want to use this function
where
what conditionally happens to where you would want to use MyFunction("1D")
Basically I'd like to change what cards my player is holding without making new instances of the UI element containing that image
How do you know you want 1D
I know I want 1D because I have made Enums that provide me with the "1" and "D" parts of the sprite name
Each card has a pair of suit and rank from those enums
and I wanted to associate a sprite to each combo of suit and rank
I'm not gonna lie I have not seen enums and attributes used in this kind of way whatsoever. Could be ignorance on my behalf but doesn't feel like the norm
Are you familiar with ScriptableObjects? seems like a very suitable and preferable solution to this kind of stuff
I know scriptableobjects, but I thought they were for storing stuff on disk and stuff, not for making simple containers for a finite number of value type combinations
So I'm going to end-up with a folder filled with one scriptable object for each unique card in my deck?
Is this a standard 52 deck? more or less?
It's basically a Mahjong set with more globally known appearances, so less than 52
Then yeah that's pretty reasonable
it sounds abit overkill at first but it's not as bad as you might think
But let's say I decide to add a new field in my scriptable object...
I'd have to edit them all one by one?
With enums I could mass-edit properties in one neat file, and could do so by rank or suit
That's why it sounded like trouble mostly 😅
There's some third party tools that can assist with it but the short answer is yeah. At the very least this is how Unity has been designed to work best with
Never a single objective solution but from what your posting I honestly do believe you'll gain more than you'll lose
In those scriptable objects I can store a specific sprite from a sheet tho... Hopefully I only have to do it once
and you can reference the scriptableobjects as an asset which can make things super handy
Actually, what's the difference between making a class to contain data and making that class a scriptableobject?
the fact that it's a serialized preset of a class that is also an asset for drag and drop related reference purposes
has more overhead by nature of it doing more for the sake of working better in the editor
I'd never need to drag and drop one specific card's scriptableobject instance, but for editing I see the point
a specific one no, but we don't have to be limited to only a single layer of scriptableobject usage 😄
another scriptableobject to contain a list of your cards for example, can be quite handy
a scriptable object is for data, you can assign it from the project window to multiple places (prefabs/ scene objects/ etc)
an MB class needs to be in a scene, so can't be reused in multiple scenes
In case I want to make different card list presets?
and if you just want a solid reference to all the cards period
eg. instead of having your sprites be found as an arbitrary array loaded in a hardcoded string path. you could just straight up have your list of cards be an asset directly referenced by your gamemanager or such
then you have a nice clean, non hardcodey way of having a list of all your stuff, not just the seperated visuals
That's kind of why I was asking this before,
Ideally however you know you need to display 1D, should also be a way to get 1D
if that makes any sense
Well it wasn't, with my card type being a combo of two different enums
I needed to combine the info from both to know the name of the sprite
yes because you didn't have a solid way to link all of that together
Is scripting in unity 6 similar to other versions? I'm trying to learn unity 6 and there is this tutorial that only goes up to unity 5 (On Unity Learn):
Scripting is the same in all versions of Unity.
There are API changes - things have been deprecated, renamed, replaced.. etc
Good to know, thank you Homer
That course goes up to 2019.3. It's much newer than 5.x
why does unity call it scripting?
C# isnt a scripting language, code written in a monobehaviour class doesnt seem like youre writing a "script"
is it just a leftover from early versions of unity?
I'm fairly sure it's because you're working in the unity framework, hence it's scripting
Though honestly the difference in this context genuinely doesn't matter
Scripting is kind of interchangeable here
It's similar to scripting in the sense that the core of the engine is written in C++ and user code is in a different language, being hosted by the C++ engine. Not much different from running Lua scripts in a C++ engine.
But it's also partially left over from earlier versions. There, the distinction between engine and user code was more solid and other languages like UnityScript (a JavaScript copy) were recommended over C#.
Boo and js weren't used much hence them being ditched
the only real pet peeve I have about the use of "scripting" is that the standard convention is to name the folder that contains most of the .cs files is called scripts. When the typical thing youd do in most other contexts is for that folder to be named some variation of source or src
it took me a long time to get a feel for good project structure, and personally I think scripts made it harder as it pushed the mentality that you need one folder per file type.
whereas now i use source which I can put folders inside to group together relavent parts of the project together, usually the type doesnt matter
canvas can if in world, ui document cannot as it can only overlay render
honestly just avoiding putting files into a folder, entirely based on what the file extension happens to be, helps a great deal
I used to seperate textures and materials then i stopped as its a pain in the ass, i put a model + mat + tex together now
so if I turn my UI in game objects that are UI objects. like, sprites and 3D text, it would work?
Good separation for materials is very good too, if some materials are for the terrain, those shouldn't be in the exact same folder as ones for a character
At some point I think I had every material live in one folder, and every texture in another. Mixing things like that is a pain
its kind of unitys fault for having a pretty featureless way to navigate a project directory
assets navigation drives me up the wall sometimes
i know theres third party implementations but for the love of god some kind of recently viewed selection please
https://assetstore.unity.com/packages/tools/utilities/vfolders-2-255470 at least there are assets like this that aim to try and fix it
I'd lowkey love to be able to lock folders to a specific parent folder too
eg. one tab that might be in some subfolder but that i will always know will be somewhere in my Assets/Project/Prefabs/
I think an issue is that the project directory in unity has an identical structure to how it would be in a file explorer, you can end up with a a bunch of nested folders in nested folders, and it can feel like a chore to try and group things together because you have to do all that yourself
No, Canvas (UGUI) can render in "world space" and then would be affected by camera post processing.
UI Elements does not support this rendering mode so its not possible to do it with this without some jank
i don't mind nested folders. quality of life features can solve a lot of the workflow pains
theres a game engine called Murder, which seems to disregard the actual structure of your project hierarchy, and instead favours putting things into grouped folders based on tags
it would be quite nice to have that in unity
but alas
oh whoops, I thought this was #💻┃unity-talk not the code channel!
Not sure if I prefer that tbh. Although ideally Unity could support both
the search window makes it easier to find certain asset types
Hey Guys i was watching a tutorial on a player controller, I wrote the exact same script as the guy but it seems like i get an error and he doesnt, can someone please help me? thanks a lot
true, but I meant that I think the actual structure of where files are located in a file manager, doesn't need to be 1:1 reflected in Unity. It could be nice to group files together in a way that is better than "put them in a folder which is called something specific"
like a smarter project folder view
"the exact same"
your is not the exact same
i dont even know why this error is happening, please help
Library\PackageCache\com.unity.visualscripting@1.9.1\Runtime\VisualScripting.Flow\Framework\Events\Physics\OnParticleCollision.cs(46,82): error CS1503: Argument 3: cannot convert from 'System.Collections.Generic.List<ParticleCollisionEvent>' to 'UnityEngine.ParticleCollisionEvent[]```
looks like youre using a list instead of an array
but it's not even my code it's internal unity stuff
oh
unity itself is mad at me and i dont know what i did
make sure all packages are up to date in the package manager, if the issue persists after updating packages then close the editor, delete the Library folder from within your project, only the Library folder as that is automatically generated by unity, then open your project again. it will reimport all assets and packages then you'll likely need to open your scene again (assuming you had one open)
I mean, can't you just put any files in whatever folder you want? Also, you can put labels (tags) on folders as well . . .
updating didnt work
deleting library folder didnt work either
removing the package works
i hope i didnt need it
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 187
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2025-05-21
this is bullying 😿
Or a reminder that this happens all the time here as a form of reassurance that you haven't done something wildly off-base.
It's up to you on how to interpret it.
Everyone was at that stage once. I remember being confused about many things when i began learning programming (java!)
does GameObject.Find() find objects that are not set active in the scene
!collab 👇 also don't crosspost
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
did you read the documentation page about the method?
public Report(ModId modId) : base()
{
id = modId;
...
}
public Report(long modIdLong)
: this(new ModId(modIdLong))
{
id = modIdLong;
...
}
Is this how you make overrides to a function?
er no
then how
i mean it works?
but i just wanna know if i really have to copy the stuff from the func itself
You need an abstract or virtual method in the sub class: protected virtual void MyFunc()
then override it:
protected override void MyFunc()
{
base.MyFunc();
}
you dont have to call the base implementation but you can
Constructors are different, they do use : base()
its a constructor
i just wanted to know if i have to like copy it again, whats inside it
so that i have this kind of result i have right now
the (+ 1 overload), so i can choose different variables in it yk
No the base() constructor call will be executed and then your additional stuff
what 😭
but i had a error when the additional stuff was empty tho
and it was only once
oh wait actually yeah of course it will be once my bad
public class Foo
{
private int myInt;
public Foo(int myInt)
{
this.myInt = myInt;
}
}
public class Bar : Foo
{
private float myFloat;
public Bar(int myInt) : base(myInt)
{
//Extra stuff
myFloat = myInt;
}
}
thanks
ive got a race condition problem kindof where this code
{
canvasGroup.blocksRaycasts = true;
if (transform.parent == transform.root)
{
transform.SetParent(originalParent);
rectTransform.anchoredPosition = Vector2.zero;
MinionManager.Instance.UnassignMinionFromGenerator(minionData, originalGenerator);
}
}```
calls when i drop my minion and will reset its position if it didnt find a valid drop point
and this is my drop zone code which makes the minion have a parent trying to prevent the reset but due to the other one firing first it doesnt work
```public void OnDrop(PointerEventData eventData)
{
MinionDrag draggedMinion = eventData.pointerDrag?.GetComponent<MinionDrag>();
if (draggedMinion == null) return;
if(MinionManager.Instance.AssignMinionToGenerator(draggedMinion.minionData, generator))
{
draggedMinion.transform.SetParent(generator.minionContainer);
draggedMinion.GetComponent<RectTransform>().anchoredPosition = Vector2.zero;
}
}```
Hi everyone, I have recently started to study programming for unity just trying to figure out where it actually pays to study.
I started with unity learn but i found it bad because it doesn't explain at basic levels the concepts of programming. i tried with the program that teaches c# on microsoft but i would like to try my hand on unity already since some concepts are different, i followed the guides pinned on the channel but some of them take me back to the manual where i wouldn't know where to start... do you have any initial advice? I may be complex but I would like to study well 🙂
Start with the basics of C#. You can use websites or blogs to learn the basic concepts. after that, I suggest the Beginner and Intermediate scripting tutorials, then the Junior programming pathway . . .
The Beginner and Intermediate scripting tutorials teach you the basics of C# in relation to Unity . . .
You need to change how your code is placed. You would end dragging before the you drop (release the drag). One definitely occurs before the other, so you need to setup what happens in the method accordingly . . .
Ok thank you
Ive had this problem before when using the event system events. I ended up delaying the drop check to a frame later but end of frame should work too (via async or coroutine)
hey i running into a small problem wen jumping im using the new input system and im using (Physics.Raycast) as to check wen my character is on grounded or not. and for the most part is work 100% of the time but now and then my character gets stuck to the ground for a few second before he will jump again
if someone can help or give pointers i would appreciate it.
private void Jump()
{
ray = new Ray(this.transform.position, Vector3.down);
if (Physics.Raycast(ray, out hit, jumpCheck, ground) && !MenuManager.instance.gameIsPaused)
{
player.AddForce(Vector3.up * jumpHight, ForceMode.Impulse);
Debug.Log(hit.collider.name);
}
}
Thanks yeah i tried that which made me realise that wasnt actually the problem lol it was a bool function failing
hi, who can help me with a script that is changing opacity at an ui image if my script debug is showing correct answer?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
Is there a nomenclature for public functions when it comes to setting or updating values? I know most people use "setX" when they want to set a value to a direct value. What if you want to increase/decrease that value by an amount? Do people use "updateX"? Or is there a better phrase that doesn't conflict with Unity naming standards?
how do i use this =))))))))))))))))))
You read it
ohh
read it? lol
In C#, you would most likely want to use a Property, so you'd just do .Thing = and it'd run the setter for you
That would also work for += and other special operators depending on type
I've heard from MANY people that properties should be private and public classes should Get/Set those properties.
Fields should be private
properties aren't meant to be private
Properties are literally designed to be public
getters/ setters are properties
using UnityEngine;
using UnityEngine.UI;
public class ImageFadeOnFeedback : MonoBehaviour
{
public NumberSlot numberSlot;
public Image imageToFade;
public float fadeSpeed = 2f;
private bool shouldFadeIn = false;
private bool isFading;
void Update()
{
if (numberSlot.feedbackText != null && numberSlot.feedbackText.text == "Corect!")
{
isFading = true;
}
if (isFading && imageToFade != null)
{
Color c = imageToFade.color;
c.a = Mathf.MoveTowards(c.a, 1f, fadeSpeed * Time.deltaTime);
imageToFade.color = c;
if (Mathf.Approximately(c.a, 1f))
{
isFading = false;
}
}
}
}
is this good
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
🙂
you wouldn't use a property in every case of the original question though.
Just use whatever you like and makes sense , it'll be different at each developer.
Increase/ Add
Decrease/ Remove
is something good in this script?
Yeah, I don't want to use a direct property setter, because - say - the player may be cursed and their hunger can't increase when curse. I wouldn't want to put that logic on every single other script that increases hunger. I'm going to use a function inside the SurvivalManager to do it.
But thank you! ❤️
This sounds like exactly what you'd use a property for
you could put that logic inside the setter for the property though, that's kind of the point of properties. you can add validation to the getters/setters because they're really just methods
Just seems like you're not reading / understanding what's being shared
public float Hunger {
set {
if (isCursed) return;
_hunger = value;
}
}
Now nothing else needs to check for the curse. Only this object cares
Ohhhhhhhhhh
Other stuff just does player.Hunger -= foodValue and the player handles it
I understand now. That's actually really cool.
It's a pair of functions that use the same syntax as a variable, but it's not actually a variable
You'd still have a private field, in this case, a private float _hunger inside the object
But you expose a property that runs whenever you change the value using normal variable-assignment syntax
And so in my "food" script (I haven't gotten this far, it likely won't be called "food"), I'd do something like SurvivalManager.Hunger += 10? And this would pass "_hunger + 10" to the value?
that is, assuming your Hunger property's getter just returns the value of _hunger
Right. That makes sense.
You wouldn't want it to return some lower/higher value based on some other condition unless there was a good reason for it.
any way to make an easier looking movement script?
Do you need to explicitly include the "get;" function inside the property definition in order for external classes to access it?
yes, the property must have a getter if you want to get it anywhere
Yes, the snippet I provided above wouldn't actually work as-is, since it has no get and couldn't use -= because of it
And the snippet above would need a full get definition: get { return _hunger } if I'm understanding this syntax error that VS is throwing. Right?
get { return currentThirst; }
set {
currentThirst = value;
}
}```
why is a movement script to hard to make 😭
yep, if you have any validation logic then it must be a full property, not an auto property. auto properties (which just use { get; set; } ) have their backing field generated by the compiler, but you are using a property with an explicit backing field
also you are currently returning the property, not a backing field so it will cause a stack overflow
oh and you can shorten up the definition a bit with expression body syntax if you want. it looks a bit cleaner
public float CurrentThirst
{
get => _currentThirst;
set => _currentThirst = value;
}
get => currentStamina;
set {
currentStamina = value;
}
}```
this would still be ok though, given that there's going to be some logic on how thirst increases/decreases. Right?
Yep
LOL, sorry, switching variables on ya.
You don't need both to be expression bodies
It's just a shorthand way of writing a one-liner
that is going to cause a stack overflow (or possibly just a freeze) because you are using the property not a field inside the getter/setter
Ok, mind is breaking a bit. Does the variable in both the get and set need to be the same variable?
_currentThirst, that is.
it can be the same variable, usually it is. but it should not be the property
Ok, understood that part. But external scripts - do they then reference "CurrentThirst" when updating its value?
yes, they will use the property not the field
Wow, ok. Cool.
Intuitive once you get into it, but totally unintuitive to return a different variable name despite OTHER classes setting the property name.
How a property works:
Whenever any code reads the value, it runs the get code. Whenever it changes the value, it runs the set code. It doesn't even need to have a variable at all, but if the set changes itself, then set calls set calls set calls set calls set calls--
So then question about syntax - I see you and multiple others use _variableName. When do programmers use variables beginning with an underscore, and variables beginning with camelcase?
Gooooot it.
types, methods, and anything public should typically be PascalCase, private/protected fields are typically _camelCase (with the _ prefix), and locals/parameters are typically camelCase with no prefix
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names
This is fantastic. Thanks!
Last Q, maybe. It says that _currentThirst doesn't exist in the current context.
Where do I need to define it?
it needs to be a field in the class
OH, its own private field?
So CurrentThirst - the property - is kinda acting like a Public class to get/set the private field, _currentThirst
correct, the property is really just a getter and setter method disguised as a variable. those getter/setter methods need an actual variable to work on
Makes sense.
although once we get c# 14 we'll get access to the field keyword for use in properties that can use a compiler generated field like auto properties use
I guess then the question I come full circle around to is - why use a Property instead of using public functions? Other than the ease of saying SurvivalManager.CurrentThirst += 10 in another class;
Does it work any differently than saying SurvivalManager.UpdateThirst(10);?
properties are just a shorter way to write those getter and setter methods, you treat them similarly to variables but you can change their internal logic without needing to either switch from a variable to a method or have extra methods in the object
Ok. And (here's me, laughing at the fact that I said Last Q three Qs ago): inside of my class when I have various logic, should I be referencing the _currentThirst field? Or the CurrentThirst property?
My gut says the former, because I may not want it affected by logic in the CurrentThirst setter. But then that seems a bit confusing.
Most likely the property, in case you're doing any functionality in the property
depends, if you don't have any validation logic inside the property then it makes little difference which you choose to directly operate with. with the exception of working with structs, a property that returns a struct returns a copy of it, so if you wanted to modify just one property of the struct you'd want to use the field or else you would have to copy the value from the property, modify it, then assign it back
How would I get the world space coordinates of the corners of this 3D sprite?
What about in Saving/Loading? Maybe that's too generic/broad a question. I imagine the player's Hunger/Thirst will be a saved value. And thus when setting it, I don't necessarily want to set it using a piece of logic that, say, checks whether the player is cursed.
Does anyone have a free character controller script for Unity 6.1?
1- wrong channel
2- there's free stuff on the asset store