#💻┃code-beginner
1 messages · Page 205 of 1
I always thought it was really cool but poorly implemented in the games
get the nearest target or whichever way to determine the target
I understand. Not trying to obfuscate, and it may not be worth the effort to explain the wider context when I'm almost certainly overthinking any performance issues.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IndicatorScript : MonoBehaviour
{
public Material indicatorOFF;
public Material indicatorON;
private bool isIndicatorOn = false;
private MeshRenderer indicatorRenderer;
private Coroutine indRoutine;
// Start is called before the first frame update
void Start()
{
indicatorRenderer = GetComponent<MeshRenderer>();
if (indicatorRenderer == null)
{
Debug.LogError("MeshRenderer component not found on GameObject.");
}
}
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("RIndicator")&&isIndicatorOn==false)
{
isIndicatorOn = true;
Debug.Log("Start");
if(isIndicatorOn){
indRoutine = StartCoroutine(IndicatorCoroutine());
}
}
}
private IEnumerator IndicatorCoroutine()
{
while (isIndicatorOn)
{
indicatorRenderer.material = indicatorON;
yield return new WaitForSeconds(0.5f);
indicatorRenderer.material = indicatorOFF;
yield return new WaitForSeconds(0.5f);
Debug.Log(isIndicatorOn);
if(Input.GetButtonDown("RIndicator") && isIndicatorOn==true)
{
Debug.Log("indicatoroff");
isIndicatorOn = false;
indicatorRenderer.material = indicatorOFF;
StopCoroutine(indRoutine); // Turn off the indicator immediately
}
}
}
}
Here i want to turn on my vehicle's indicator light on when i press the RIndicator button and off when i press it again. However it never seems to enter the if condition in the while loop, i check using the Debug.Log, why does it not enter the if condition, my indicator does not turn off
In the future, with scripts this long, use a paste site
The actual dash would be easy, the hardest part is gonna be implementing this alongside your movement code. Likely would be easiest as a state machine
Ok mb
Checking input in a coroutine like that is gonna be unreliable.
So what should i do?
Just remove the isIndicatorOn condition from update
And have it either start or stop the coroutine inside that condition depending on its current state
Coroutine routine = StartCoroutine()
You can store the instance to the currently running coroutine in order to stop it easily
I'm not sure that's the problem.
Ok, but i want it to stop when i press the key again right? So what if it just restarts the coroutine?
And do a toggle like this isIndicatorOn = !isIndicatorOn
No, I just meant for an entirely new way of doing it
Check it in update and cache the input. If it's true, only reset it to false after processing it.
Imo, the coroutine should only handle blinking
Yeah, refactoring the coroutine might be a good idea.
yeah you'd need some precise skill to call that button down there
Is that like a one frame thing?
Is what like that?
Oh, for the coroutine to catch the update? Yeah
One frame every second
I see, so i get rid of the condition to check for the button from the coroutine and throw it into the update condition
Nah, use the same condition you have already
Just dont put it in the coroutine?
GetKeyDown is one frame yes
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("RIndicator"))
{
isIndicatorOn = !isIndicatorOn;
Debug.Log("Start");
if(isIndicatorOn){
indRoutine = StartCoroutine(IndicatorCoroutine());
}
else StopCoroutind(indRoutine);
}
}
private IEnumerator IndicatorCoroutine()
{
while (isIndicatorOn)
{
indicatorRenderer.material = indicatorON;
yield return new WaitForSeconds(0.5f);
indicatorRenderer.material = indicatorOFF;
yield return new WaitForSeconds(0.5f);
Debug.Log(isIndicatorOn);
}
}
}
Rough code cause I'm on my phone
The check inside update needs to have an internal if to turn on or off the coroutine
You got rid of the part that turns it off, so what ur trying to tell me is if i press the button again i toggle the isIndicatorOn value in the update and it doesn't access the coroutine right?
Yep
Gotcha
Thank you
I updated it, but this way indRoutine still needs to he checked if it is null or something. But that should give you an idea
Phone coding just sucks haha
Ye its hard to read
Can I make a value show in the inspector but be inmodifiable? Cause I would assume is just tag it as [Read Only] but it is not letting me
ReadOnly attribute is NaughtyAttributes or Odin
otherwise you can inspect private values with Debug mode in inspector
You mean Debug.Log? Cause I would very much prefer to have the values showm on the item that I am checking than having a thousand console logs
nah I mean you can pop out the script and press Debug mode in the inspector, let me show you
Just tried it and it works! Really appreciate it, now that i look at the code, it makes so much more sense lol

Awesome, glad you got it!
Ok, so I have literally done anything today other than refactor code and references; probably I would still be missing some parts, tomorrow I will probably yet find several null reference exceptions aaaaand my internet just run out for the third time... But still I think today I learnt a lot more than other days where I did tangible stuff, so thank you for that guys 😄
awesome work! you're in the beginning stages anyway, where you need to basically start creating your own workflow based on what you learn and refactor, once you get that going it gets easier and easier
so someone other day rec'd me to use cooldown, so i made this script
// Update is called once per frame
void Update()
{
if(comp.cooldown > 0)
{
comp.cooldown--;
}
//Debug.Log(comp.cooldown);
}
public void refreshServerList()
{
//delay
if(comp.cooldown == 0)
{
comp.cooldown = 1000;
}
else if(comp.cooldown > 0)
{
return;
}
//...
is this ok or is there better option?
you should never compare float with == btw
ok
has good example of doing a small timer/cooldown
You can use Coroutine too
Anyone got a good tutorial of how to make vr boxing game?
thats a very specific thing, not likely to find something like that lol
thank
aw ok
do you know any way to get started
Yeah I would start with the Unity VR learning path
doing boxing should be easy once you figure out how to even move hands, the rest is easy collider work
@cobalt creek IS it a float? Seems like an int?
Generally timers are done by subtracting Time.deltaTime from a float
But you just decrement a value every frame
Which means it will be faster and slower on different computers
DEFINITELY not how you want to do it
no, it not a float, it a variable from a script with my own custom namespace
well, where it comes from is irrelevant. It's either a float or int
int sorry
Gotcha
int for cooldown ?
yeah, then a == comparison is fine
(Ignoring that doing a timer like this is bad)
but yeah I assumed it was float lol
thank you
but yeah you should use Time.deltaTime for something like that
void Update()
{
if(comp.cooldown > 0)
{
comp.cooldown -= Time.deltaTime;
}
//Debug.Log(comp.cooldown);
}
public void refreshServerList()
{
//delay
if(Mathf.Approximately(comp.cooldown, 0))
{
comp.cooldown = cooldownTime;
}
else if(comp.cooldown > 0)
{
return;
}
//...
just slight changes as discussed so you can see
thank
But I would have the timer setting in update, and just call refreshServerList one time when the timer goes off (without even referencing the timer at all in that method)
Nav put an example link above
Oh, that was to Time.time, which is another way to do it
How do i fix this ?
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
i just learned about 'static' and i dont quite understand it but from what i am reading i can remove:
public ImageDatabase imageDatabase;
public ItemStorage itemStorage;
public JobManager jobManager;```
and just use JobManager.DoThis(); if the script in JobManager is static?
You should only make specific things static
ie non-gameobjects etc
but yes when you make the class static you are using the class directly
static is also very useful for making a specific instance static
or just a method, or extension methods
thank you for helping, now i will read up on what a non-gameobject is and what an instance is
non-gameobject meaning it can be anything just dont use for gameobject
MonoBehaviour basically
oh i use MonoBehaviour. so if its a scriptable object it can be static?
no
no not that either
and it kinda works like a static anyway
you probably don't want to make the class itself static most of the time. You'd want a static accessor (like the singleton pattern I linked above).
The cases where you DO want a static class are usually for "Extension Methods"
You don't want them to store state, you want to pass in data, let those extension methods transform it in some way, and return it. Like the c# Math class (not unity Mathf though, funny enough, which is a struct)
If you want to access state and variables, I would go with a singleton
but static class would be best like this:
public static class MyClass { }
It inherits from nothing
or classes that just perform specific tasks
Debug.Log is a good example of static function but its not the class thats static
ok i think i understand, https://paste.ofcode.org/XpZq67JrCbeiiUYwySxAwG this can be a Static because info goes in, and it just sends info out?
While yes, I feel like this would make more sense as a singleton, that way you can modify them in the inspector
note that if you use static you cannot use fields in them
they would also need to be static
though you could make all those floats just a struct
and make that field itself static
ie you cannot use non-static with static
ok, so i learned something i dont currently have a use for, but its good to use for other things.
Hahaha, that is fair. It's always good to learn!
yea its fine. I was just on Codewars and it wouldnt accept my code so i looked up the solutions and everyone was using static and i couldnt understand why. my game doesnt or cant use static so thats probably why i never ran into it.
thanks!
it fix ?
yessir
nice!
fixed but is there a way for me to see them in different colors for each one of them?
like if is pink
wait that doesnt seem configured fully though
ur missing quite the colors
i mean it works on unity
how do i configure them
which one of the step u missed, did you do the part of selecting editor in unity?
If you did all the steps in that guide, you may just need to click Regenerate Project Files in the External Tools menu
yes i did
click Regen Project Files. make sure vs is closed, reopen script from unity
still no colors
screenshot the Solution Explorer in VS
even though regen project files should do , might need to manually right click the solution and do Reload with Dependenicies
or w/e is called
umm where is solution explorer
In visual studio 😺
[ToolTip("HelloWorld")]
or you mean [Header("Hello World")]
which one did you click
did you not install the workload ?
yeah that usually happens when you dont have the Unity Workload
oh mb when i first downloaded VS i was learing coding and wasnt planning on downloading unity, etc
ty, i have always hated that VS opens when i accidently double click one of my scripts. I never knew i could just change this to Notepad++.
so this is gonna fix everything ?
yeah it will fix it , make sure you have it
oh lord..
maybe on my next game I'll choose a "better" IDE.
thx @rich adder
NO! 🫠 🤯 😭
its beautiful
Oh my god, it wasn't a horrific distasteful joke
I never had a teacher, im self taught. well ChatGPT has been helping me learn for 1 year next week.
this is horrific
gpt has taught you wrong
why do you have a forach loop outside a function
and if its inside a function , why do you have local functions..
Are you trying to upset us?
its in clearSave, my tabs are wrong
GPT is the worst
please use a real IDE
Notepad++ is not an IDE (and a configured IDE is required to get help here #📖┃code-of-conduct )

wait My IDE is configured, it underlines errors and Auto completes code. dont scare me. also you sent me to community-conduct instead of read-me, which i read 5 times thinking i missed the IDE requirements.
while i like np++ i use vscode more now
Hi ...
Ah,yeah wrong link sorry. I just know the mods have told people to use a real IDE before when they use NP++ or risk being kicked
i have a problem
what u problem, just say directly the problem
same, i use NP++ =\ let hope yours is not as serious.
I codded a top down enemy chasing Ai
its working but the enemy is not going directly to the player
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AIchase : MonoBehaviour
{
public GameObject Player;
public float speed;
private float distance;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
distance = Vector2.Distance(transform.position, Player.transform.position);
Vector2 direction = Player.transform.position - transform.position;
direction.Normalize();
float angel = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.position = Vector2.MoveTowards(this.transform.position, Player.transform.position, speed * Time.deltaTime);
transform.rotation = Quaternion.Euler(Vector3.forward * angel);
}
}
Simple one
hey if i want to check the velocity of an object is the only way to store it as a vector3?
or can i do it as a float
you can store the .magnitude and store as float
Its like that
But you aren't moving towards the player.... sooooooo IS it like that?
what ??
Yeah, I guess the issue is not the rotation is it
Can you explain the issue better please?
Who said error?
The player is the circle?
yes
Thennn... looks like the rotation IS the issue, and I think it's because Atan2 is used incorrectly
Try just using RotateTowards, right?
To clarify, your issue is that the triangle is pointing the wrong way?
It COULD also be the pivot point
what should i do
Try just using rotatetowards
How to use it correctly ?
so?
dont use a screenshot
copy paste it
with 3 of these` on bioth ends
change update to fixedupdate
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 5.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// We'll move the vehicle forward
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
}
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
okay
it gives me error
which is?
too many of them, I think I didn't do the right thing, i'm really new at this
what did you change
void Update to void Fixed Update
perfect
wdym
Now it doesn't give me error
ok
And now, how can I fix the car movement?
i followed a tutorial for this sokoban top down 2d game
what is the purpose of the sqr magnitude?
if its afte a normalise is it not always just 1
If there's no input it's 0
sqrmagnitude is faster than magnitude (by removing the sqroot)
it's to check if there are any input
it doesnt make a whole lot of sense. Most beginner tutorials really are not good, and you are seeing that here.
Checking for a square magnitude of 0.5 means they are checking for a magnitude of sqrt(0.5) which is like 0.7071. This part has no specific reasoning because the magnitude will be 1 if it has input.
Even if they did not normalize it, they are using GetAxisRaw so the magnitude would be 1 at minimum if there was input
Hey! One of the tasks in my project is to "paint" over an area, I have that logic figured out. My issue is with figuring out how to check if the task is complete - my colelague wrote a piece of code that creates a 2D array of bools with the size of the target texture and checks when he paints each pixel, but that feels... weird, could anyone suggest a better path to take?
Ehh a 2d array of bools is probably fine? You could have a touched or untouched Set to which you add/remove values to keep track of which pixels have been painted, but I don't actually have a strong argument for why that's better. If you're worried about having to loop through all the pixels you could process them in a shader instead which would make that a non-issue
it doesnt actually loop through them - it uses a counter and textureCoords
yeah i was just thinking that didn't actually make sense
the reason you'd do this 'as they paint' is becaue that way you never have to loop through them
if you wanted to do the shader thing it would make more sense to not track anything as they paint and just process the whole image in a shader to look for pixels that are the 'unpainted' color or whatever
which would probably save you some memory and might be worth it on large images?
but adds a lot of technical complexity to what's going on
you might be able to get away with just the counter depending on how the painting works
but it's often nice to be able to have info about which pixels are unpainted, not just how many, both for debugging and so you can tell the player if you need to
I am making an AR app, is it possible to make a small menu that starts on the start of the app?
Menu with 4 button, each button take me to a different ar experience
Is it possible?
what happens when your app starts is purely up to you. if you want a Menu make a menu.
hello guys, i have an issue i will love it if u can help, i want to get a script with "FindObjectOfType" however its not very good for the performance so is it better to use "FindGameObjectWithTag" then use "GetComponent" to the refrenced GameObject or not? i hope u can help and thanks!
would that not do the same thing
Better to do neither and have a direct reference
@long furnace don't cross-post. I've removed your other questions
If you're wondering about their differences in performance, profile it.
i wish to however its an instantiated Object and this is the best way i found
what dose that mean
look up 'dependency injection'
ok thanks
Posting to multiple channels at once
lmao this is way to complicated, dont u know who is just faster? im not that advanced at coding .edit Thank you so much i found a way to set a refrence already
thank you too!
what's the difference between doing,
public Action OnUnitDie;
and
public event Action OnUnitDie;
is it just for better IDE suggestions?
An event can be only invoked from within the struct/class which declared/derived it
event and delegates
not sure if this is true
i can invoke that event in other classes just fine
You can via calling a method, but not directly
action is just a predefined delegate with a void return
okay yea i cannot
I have noticed that without event keyword i cannot do some kind of missclick, like I cannot do
LoadingManager.Instance.OnSceneLoaded = null;
but when i remove the event keywoard from public Action OnSceneLoaded
then i can do that just fine
possibly missclick and write = instead of +=
so i guess it's better to add that event keyword for more security?
yes you cannot assign it from outside class that declared it with event keyword
only += and -=
yeah, I don't really use delegates outside of events, unless I'm binding methods to some identifier like through a dictionary.
I guess I do pass around interfaces sometimes with method implementations to substitute some of that functionality instead.
yea that makes sense
I wonder if there is a way you can modify c# scripts in unity to act more like how python does no ; no {}
No
Well…you could with some codegen but that would be more work than just getting used to ; and {}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
How? Do you have a resource on that? never used one
I actually dont like it
Im already used to it but I dont like it
python so ugly though, why would you want to make an actual project with its syntax
I like it better
Hero you go, but you are simply going to make your workflow much harder for zero gain
single scripts ok, but trying to figure out what I was doing with it usually requires me writing double the comments ;)
thanks man. my motto is work harder not smarter anyway
I can already imagine a lot of pitfalls if they're gonna codegen to add semicolons and braces...😂
I mean, it's basically writing your own language or compiler. I always consider it a task for the smartests in this world.
you can turn any language to given syntax (grammar) by rewrite the parser and tokenizer and ast......but it literally becomes other language....
Im actually dumb
Maybe reconsider then
There are all kinds of programming languages, gotta accept that fact.
no. My father said even if you are dumb if you are dedicated enough you can do anything
Aight. Good luck then👍
If I'm gonna have to deal with python in C# I'm gonna shoot myself lol
You can still use python in other ways like level gen and then parsing it in unity
I use it to quickly parse documents and export it over for some word game I was making
btw you can use any languages you like if you know inter process communication
serialize everything to be byte stream then deserialize it
yeah, python has a lot of libraries for AI and pathfinding which I can see being some utility for your project
Thanks. I do not. Gotta learn
I made pacman in pygame where I'd make the levels using wingdings in worddoc then importing it into my project
Thankfully C# is neither.
You'll still need the logic in C#. Or at least an interface that would interpret the messages from the python side. Not to mention that your game would consist of 2 processes.
"if you shoot yourself in the leg c# default you will not face any problems because the bullet will be plastic, but if you modify it and try and write hello world your gonna have some serious problems because the bullet will be a nuke then." -albert einstein
am I funny?
Not really
I just hope you know that braces and semicolons is not the only difference between C# and python
I know. I used pyhton since I was 13 (Im 20 now)
Did you use C# though?
ehh mehh. not an expert
but I definietly used it. I have 6 completed projects in unity
as I said, i will share it here once Im done for free. something useful for community.
yikes
goodbye.
See ya in like 6 months to two years
"fools rush in where angels fear to tread" - Alexander Pope
Because its private no one can see it
but the tutorial guy put it in private
The tutorial guy is wrong then
but it works on his video
The sneaky private switcheru
switched to public still cant see it
I think somewhere digiholic’s counter is going up by one
Did u save the script?
it doesnt matter
but its in the start
what is in the start
restartlevel
why the function is inside start?
again tutorial guy put it there
its not in the start in your screenshot
do you have compile errors ?
its not in the start that was the problem
I know it wasnt the start
umm still cant see it tho
rip
ill just do other ways of restarting the level ig
where are you trying to call restart function
in death animation
I mean object
you mean where is the script in ?
yteah
Player
Hello
hi
ENTIRE THING
THERES A LOT OF TABS
I mean entire thing where script is seen
where you trying to call restart level
in death animation i already told u
Where is that death animation
im pretty sure you cant call function from scripts in animator
the thing is other scripts shows up
Is there actually an animation?
an odd way to do it tbh, but regardless. When following a tutorial, if it works for them and not you... you've done something wrong/ missed something, go back and rewatch
i can see other scripts
yea ik the guy in the video also said ' you can just make count down'
so, you can't see your PlayerLife script where this method is you want to call, in this dropdown?
yes
re-read the list, closelierly
it should be RestartLevel there
no it shoudlnt
no
RestartLevel is a method, not a script
well technically you can, in inner class
RestartLevel is IN the PlayerLife class
he was trying to call it completly outside
perhaps, it would be a good idea to learn the very basics of C# ... what a class is, method, the setup of them etc
video is 2 years ago older verison of unity maybe thats why?, cuz on video it instantly pops up
dunno, without seeing the video. But if it differs, this highlights why you should do a tutorial on the same version
maybe you're right and i need more classes about c# after all
what tutorial
tutorial guys suck at writing good codes
dont watch beginner tutorials learning c#
they suck
go to learn unity
why everyone ask everything in code channels 🤔
laziness, stupidity, lack of care
Ever wonder why you always end up in an endless loop of tutorials? Are you worried you'll quit your next big game project? Well, in this video, I cover exactly how game dev tutorials might be stopping you from doing just that!
Get your FREE Indie Game Starter Guide: https://www.judicamegames.com/starterguideform
Watching after i take a tutorial lmao
add wilful ignorance and you are describing 90% of the people asking questions
you can watch tutorials on specific topics where you are stuck but for beginners and for learning from scratch they succ
Would a steo by step beginner tutorial be the same? Such as https://youtu.be/XtQMytORBmM?si=Uvo8tOQT5D9_qH8q
🔴 Get bonus content by supporting Game Maker’s Toolkit - https://gamemakerstoolkit.com/support/ 🔴
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...
I hate them so much. they dont teach you fishng they give you fish butthat fish is only one specie. and you cant change the fish later when you try from svratch let alone being able to fish
this one is good
most of the unity "TUTORIALS" just teach you bad code
with bad architecture
that is non extensible
Yeah cause I was like. This so for has helped me the best
and hard to add new things
not-designer friendly
and just bad and non-dev friendly to work with with plenty of bad practices
does it work? it does, but is it good? most of them are terrible
my man. If you feel you are learning you are in right path. If you feeel just copy paste and dont know why that guy does that writes that then wrong path
brain shouldnt be on autopilot
True
Gm is a great guy. since he studied the art of learning hence can make a great tutorial
I just wish someone would create structure. Do these kinda tutorials and indicate where the user can improve it and send them to a doc all about it if they want to learn those things
code architecture is a thing you need to learn yourself mostly
based on many projects done
many trials and errors
many abandonded projects due to bad architecture
then you improve on next project etc
Even going through gms course. I'd see little things like making a boolean return method == true in an if instead of just leaving the method in paraethesis. Shorter and also works
vs underlines it in red not hard to miss
Exactly
just hope that all you write doesnt change colours😂
i used to hate ;
But then I realized using // to make multiline code is so much more obnoxious
i have embraced the semicolon
Was the GameObject.SetActive is delayed for end of frame or immediate?
It occurs immediately.
I thought it was at the end of the frame . . .
Hello, I’m doing a code where inputs are in update() and physics calculations are in fixedUpdate().
A cooldown mechanic is being added, should it count the elapsed time in update() or fixedUpdate()?
Like, should it go along with the inputs or in sync with the physics?
What is the cool down for
it depends
I would keep cooldown timers together with whatever they're a cooldown timer for.
A dash
Destroy() is at the next frame
SetActive() is immediately
I'd probably do it in FixedUpdate
Thank you, just realised it’s better that way too because of how inconsistent it’d be with the FPS 😅
That is not a problem.
given that you're already handling user inputs in Update (as you ought to be)
I'd probably lean towards handling all cooldowns in Update just for consistency's sake -- especially if I also check the cooldown timer in Update
Yeah I am, when I put the CD calculations in update() it feels out of sync with the game’s physics at low fps though
Yes, Destroy is at the end of the frame, but I thought the activation/deactivation also occurs at the end. I know the flag will set the active state immediately . . .
well now I'm not sure :p
it's on the next frame actually, not at the end of the frame
i'll have to check now
how can I get a variable from one game object and put it into another
game objects dont have many variables, do you mean components on game objects?
gameobject1.GetComponent<A>().variable = gameObject2.GetComponent<B>().variable
gameobject1.GetComponent<A>().variable = gameObject2.transform.GetChild(x).GetComponent<B>().variable
thats good
how can i make it? is there a tutorial?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i am followung the guide for ar there, but i dont like ti that much tbh
isnt ther another guide?
yt is full of them, mostly crap
I'm not sure I understand what I'm doing so I'll give more context: script (PlayerMovement) needs to rotate the object it's attached to (Player) by the amount of the variable yRotation which is created and valued in a script (PlayerCamera) in Player's child (PlayerCamera)
thats pretty ez man
well, i just think that i need to understand scene manager and how to use button, also for that youtube is bad?
well from what I'm doing it's getting the variable as 0
send cods
yes, because the problem is you will not have the knowledge to know if they are bad or not
were do i have to check in unity learn?
would you like me to take the lessons for you, save you all the effort
they wont load myman
stuck here for minutes
damn
go scrrenshot
if you dont want to respond is not my problem, just dont respond 🤷♂️
bro hes just trying to make you find things your own chill. google js way better than individyals about specific topics
you say that youtube is bad and i need to use unity learn, i ask "were on unity learn?" and you dont tell me. how am i supposted to know erer things are on a website that i almost never used?
what are those comments??? is it fron chat lgbt
no
google find me youtube
I tried to do it myself but some of the code was from videos
so I tried to understand what it does
hello i wanna make a game about ...x where you .... and i also wanna make enemies ..... and j wanna make them ...... too do you have guides on that? bro ifur gona make something special better make it yourself
make myself something i dont how to make because i dont have aguide
you see something that isnt youtube?
that just confirmed what i said
@dense cypress ill take a look in a sec im not on pc those codes i cant read my phone is bugged cant zoom discord images
ok
no it didn't, you said "next frame"
well, after the entire Update loop
can be interpreted in both ways
either end of current frame or start of the next noe
but there is still a lot of the current frame left at that point
@turbid robin 100 bucks. i do what you want
okay yea fair enough
but what if i called Destroy() not in the Update
if it's called in Update then it will indeed happen after the current Update loop
but if it's called somewhere else, let's say in OnTriggerEnter
then it will be destroyed after current frame
trigger events are processed during the physics loop which occurs before Update . . .
not related
what
its kind of a riddle. can you find it out
the playermovement only wants to rotate on y if that's what you mean
because I dont what it to fall over
which script
playerm....
wait do I put ``` yRotation = camera.GetComponent<PlayerCamera>().yRotation;
yeah I did it works now thanks
why did you put it
how did you know you had to use it 🧐
actually you should put the GetComponent part in Start and the yRotation=yRotation part in Update
It occured to me after you said to put something in update
what does yRotation=yRotation do
I hope your not asking chatlgbt
thats too complicated for a beginner but anyawy 🤨
is it?
but you are not really understanding any of this are you
hmm good legit
chatgpt didn't deserve such slander
you cannot slander a LLM, just the dumbasses who trained it
I will be among first ones to die when AI takes over the world
That's why ai decided to enslave humanity.
anyway now I actually have functional player controller I can actually make game
wait how do I increase the gravity on a rigidbody
just as default
2d or 3d?
3d
One rigidbody or all?
Yesterday I actually wrote codes for that might as well share ithere
I only have one rn but probably everything
So search for how to change gravity
If it was 2d you can change it per-rigidbody, but 3d uses a global value
this is a hint
do the rest yourself
you can actually optimize by Physics.gravity *= changeGravity but thats not how I do it so
If I have a child of a UI object. How do I get its actual position in the world, not the one relative to its parent? Would that be anchoredPosition?
no
Gonna elaborate?
transform.position should be it.
And if it has a rectTransform, transform uses that rectTransform?
Because it's a UI item
yea
RectTransform extends Transform, so yes.
I have a very good opinion. we add google to this server and make googling for 1 minute mandatory before asking quetsions
Just like not responding with Noto a How? question should be mandatory?
I responded to Would that be anchoredPosition
Yes, very helpful indeed
Idk man. maybe try copy pasting your question next time
Think I'm being stupid here.
I'm trying to have the health text animated so that if the character takes 5 damage, the text goes from say 100 - 99 - 98... 95
With my current code though, I am giving 5 damage to the player, but the damage received seems to be like 5.something as the health text ends up as 94.9672 or something like that.
Any ideas?
public void ReceiveDamage(float damage)
{
StartCoroutine(ReduceHealth(damage));
}
private void UpdateText()
{
healthText.text = currentHealth.ToString() + "%";
}
private IEnumerator ReduceHealth (float damage)
{
float damagePerSecond = damage / smoothDuration;
float timeElapsed = 0f;
while (timeElapsed < smoothDuration)
{
float currentDamage = damagePerSecond * Time.deltaTime;
currentHealth -= currentDamage;
timeElapsed += Time.deltaTime;
// Update health bar where max health is equal to 0.5 fill amount
healthBar.fillAmount = (currentHealth / maxHealth) / 2;
if (currentHealth / maxHealth * 100 <= 40)
{
healthBar.color = criticalColour;
}
UpdateText();
if (currentHealth <= 0)
{
currentHealth = 0;
UpdateText();
// Die
}
yield return null;
}
}
wohoho the great chinese wall
you can, you need to create scope for each case
so what happens when you divide and multiply and do all sorts of things to some numbers? would they likely be int?
same as always { }
i dont know why there are lines between my tiles
Sorry for the late reply, I was trying something
Where would you suggest exactly? I've tried just rounding hurrentHealth after applying the damage, but instead of losing 5%, it loses 3% or so
Coroutines are not precise to the millisecond, as they can only run once per frame at a very specific time. Then there are floating point errors and weird math and it all adds up to an imprecise value.
X_X
Hmmm
I was basically following along to a youtube tutorial for this which is why I've been more confused as to how it worked on the video but not for me
Either use a Lerp or a MoveTowards to transition a value smoothly and precisely.
This code would produce different results at different frame rate, so perhaps it just happened to work for them in their environment.
Or you missed something in the tutorial 🤷♂️
h1mmmm
Ah okay.
The tutorial is only a few minutes long and i've checked multiple times so I don't think I missed anything 🤔
I'll have a look at where to use Lerp then
Essentially yeah, I applied what should be 5 damage, but the health text showed it as 97%
oh
you only rounded health?
I think I see now
do you want my vesrion of the code?
It work on my machine 😄
Sure, would appreciate being able to see a different version 😂
Thanks
Just what you didn't need lol, always the case 🤷♀️
so can someone help me with this please? i couldnt find anything
Anyone have any experience with changing the colour of shared font materials in code? All my searching so far suggests I should use Material newFontMaterial = textMeshPro.fontSharedMaterial; but newFontMaterial.color = newColour doesn't seem to make any changes.
in edit mode, when selecting the tilemap, the tilemap shows a grid
yea true
so idk what the problem is. there is no problem
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
im talking about game window
and if you enter play mode
the gap is still there
I actually just remembered thta we could copy paste with rmb
are your sprites set to point filter, and no compression
they look blurry
and are the sprites on a sprite atlas, because i assume they are not
and is the actual sprite brought in as 16x16
i assume the answer to all these questions is no
yes the point filter fixed it thank you
for reference, when using pixel art, you always need to set point filter, no compression
@mild mortarwait did you fix it?
otherwise your sharp pixels get blurry like a jpeg
understood thank you
and add the image file to a sprite atlas
I haven't no 😓
if you get spam from someone in the server, let a mod know about it
otherwise, uh, idk just block
yeah
wait dont try my code
Just gonna give it a shot now, thanks 🙂
god Im really stupit today
good evening
I am using unity 2022.3.8f1, am following a tutorial that uses IMGUI(for debugging purposes). the IMGUI buttons show up in the built version but not in the editor; is there something I need to enable for IMGUI buttons to show up in the editor?
Seems to be working fine there 🙂
The actually current health still seems to have that thing of being like 89.8216 etc
But the text displays it as 90%. Just gonna hope and assume it's minor enough that there isn't a problem caused from it
Are the buttons blank?
Or are they completely missing?
they are completely missing
Maybe an exception is being thrown
how? I think I wrote roundtoInt
Check the player log file.
im a bit high today
editor with gizmos on
build
note that you don't need Gizmos on to see IMGUI graphics
That's the problem.
Your game view is zoomed in.
np!
I had a problem on my Steam Deck where the default font just...didn't work
so I had to set the default gui style's fonts on startup
Yeah the text is rounded, I just meant the behind the scenes actual health isn't rounded, so hoping when calculations and stuff come in, that the player isn't really affected from a build up of those trailing digits
it can accumulte
is there any way of checking if ray Hit the Object head inside the Player object like the Health component but detect if the Ray hits the Head object instead
void Fire()
{
recoiling = true;
recovering = false;
Ray ray = new Ray(camera.transform.position, camera.transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray.origin, ray.direction, out hit, 100f))
{
Health targetHealth = hit.transform.gameObject.GetComponent<Health>();
bool isHeadShot = false;
if (targetHealth != null)
{
Debug.Log(hit.transform.name);
string vfxName = isHeadShot ? hitGoldVFX.name : hitRedVFX.name;
PhotonNetwork.Instantiate(vfxName, hit.point, Quaternion.identity);
int damageValue = isHeadShot ? headShotDamage : damage;
Debug.Log("Damage to be done " + damageValue.ToString());
hit.transform.gameObject.GetComponent<PhotonView>().RPC("TakeDamage", RpcTarget.All, damageValue);
}
else
{
PhotonNetwork.Instantiate(hitWhiteVFX.name, hit.point, Quaternion.identity);
}
}
}```
RaycastHit includes a collider property
This tells you the exact collider that you hit.
transform can point at either the collider's Transform (if there is no parent Rigidbody) or at the Rigidbody's Transform (if there is one)
So, you can do something like this
if (hit.collider.TryGetComponent(out Hitbox hitbox)) {
damage *= hitbox.damageMultiplier;
}
Yeah, so I guess it still has the same kind of problem then
create a Hitbox component that lives on the same object as the collider
currentHealth = Mathf.Round(currentHealth * 100) / 100 (I think its is 100 yes? but I THought of this before but it may make it less smooth
so I didnt
do you want to show a percentage?
So i can do like Debug.Log(hit.collider.name); To see what its hitting and should say the Head if head?
his problem is
please help him
$"{0.123:P0}" will produce "12%"
$"{0.123:P1}" will produce "12.3%"
etc.
the general form is {expression:formatinfo}
Yeah, I followed along to a tutorial and just want the health to display correctly and also smoothly decrease on the text when damage is taken
P0 means "percentage with 0 decimal places"
the code above should fix it but it may not make it as smoothly
That'll display the health percentage properly.
To make it change smoothly, you'll want to track the displayed health separately from the actual health
Assuming these are both percentages already, this will change the displayed health by at most 20% per second:
displayedHealth = Mathf.MoveTowards(displayedHealth, health, Time.deltaTime * 0.2f);
You can then use string interpolation to turn displayedHealth into a nice percentage
I'll try that then quickly, thanks
healthText.text = $"{displayedHealth:P0}";
I believe this will round to the nearest hundredth
rather than rounding up or rounding down
damn yeah this makes sense
so 0.3% health will become 0%
If my mind was in its place I'd definietly recommendthis 100%%
hello im tryna make a code that destroys the player when the player collides with a spike
but instead it destroys the parent and its childs
can i make it only destroy the parent?
you could unparent the camera first
I would suggest just making the camera follow the player
@swift cragyou seem experienced in this stuff. do you mind telling me why my code kinda works but not as smooth? I actually know why but I cant get to fix it
Cinemachine would be ideal.
whats that?
So in the case of my code here, how would you say to implement this best?
public void ReceiveDamage(float damage)
{
StartCoroutine(ReduceHealth(damage));
}
private void UpdateText()
{
healthText.text = currentHealth.ToString() + "%";
}
private IEnumerator ReduceHealth (float damage)
{
float damagePerSecond = damage / smoothDuration;
float timeElapsed = 0f;
while (timeElapsed < smoothDuration)
{
float currentDamage = damagePerSecond * Time.deltaTime;
currentHealth -= currentDamage;
timeElapsed += Time.deltaTime;
// Update health bar where max health is equal to 0.5 fill amount
healthBar.fillAmount = (currentHealth / maxHealth) / 2;
if (currentHealth / maxHealth * 100 <= 40)
{
healthBar.color = criticalColour;
}
UpdateText();
if (currentHealth <= 0)
{
currentHealth = 0;
UpdateText();
// Die
}
yield return null;
}
}
It's a package provided by Unity. You create virtual cameras that control where the real camera goes.
If you don't want to jump into that immediately, you could also just use a Parent Constraint on the camera
the Parent Constraint makes an object act like it's parented -- it moves and rotates as its parent moves and rotates
what is that aswell ;-;
oh
u said it already
@mild mortarIs this what you want?
it's a component!
didnt see it
Add a constraint source, drag the player into it, position the camera how you want it, and hit Activate
In one sense yes, wouldn't want the player to be alive because they 0.3 health
imagine this says "Player" :p
well, 0.3% is still more than 0% (:
damn not fair man
Mostly dead is slightly alive!
Oh my bad I wrote that poorly
I meant in terms of the health text
Wouldnt want it to say 0 but still be alive I meant
oh, no, I was right all along (:
When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. If there are two equally near representable results:
You'll still need to adjust the number, then
it generally makes more sense for HP to be an int, not a float
this is a percentage
(use ceil and cast to integer)
it is easier to deal with discrete rounding errors than to deal with float nonsense
float correctedHealthPercentage = Mathf.Ceil(healthPercentage * 100) / 100;
healthText.text = $"{correctedHealthPercentage:P0}";
then cast the int to a float for display purposes, but the underlying actual value is an int
like so
Then you can have nothing that deals less than 1 damage
At a time
Is it only me who thought about clamp?
and now you can deal 1e-6 dmg instead
It might fit fot some games tho
Yes, because how is that related
Using a float means that your minimum damage amount is now...wishy-washy
integers have a pleasant concreteness to them
you know it'll always behave properly
yeah, you need the very fixed nature lf ints to avoid float weirdness
I can't remember the last time I saw a game handle health as a floating point number
of course, continuous damage is a lot more annoying to do with ints
you have to chunk it up
Yep, that's what I thought. But the tutorial I followed along to put it into floats for some reason so I just went with it 🤷♀️
how to reference a gameobject like the player in code?
and slight differences suddenly get really important
i would rather use a big int for resolution, than use a float
Thats a decent option
It's fine, just use that ceiling method I linked if you worry about displaying 0 health, and it's fine. Handling health as a float is fine but it's weird displaying it as one
if 100 HP is not enough, try 10,000,000 HP. And use properties to display sensical numbers
guys what about clamp so we may get rid of accumulation problems??
if numbers can get big, you should use a long for HP
Do you know what clamping is?
clamp confines a value into a range. it doesn't help you at all with rounding
yes
You mean Max?
I doubt it
yea
pokemon gets into issues all the time because they used SHORTS for HP. One of the dumbfuckiest programming mistakes to make in 2022
just do "public GameObject Player;
If health goes below 0 due to small value it may accumulate
Floats fail much more gradually than ints
they behave similarly for small numbers and for large numbers, which is a nice property
I wonder what the point of using such a small value would be in the first place when you develop a game with no networking
You just shoot yourself in the foot with it
idfk. there is literally no reason to actively choose to make this small number a short vs long
or even a regular int
the relative precision around 1 and 1e10 is the same; integers' relative precision goes up until you hit the maximum integer, and then they abruptly fail
yes
thats right
not my point tho
pokemon has a lot of performance issues, but using shorts vs longs for HP is not doing shit, capn
float HP only makes sense for the cookie clicker hero clicker things
I don't think anybody knows your point considering you are suggesting a totally unrelated method
where you are storing values actually on the order of 10^200
floats are great when everything scales up together
multiplying 1 by 0.1 is roughly the same as multiplying 1e20 by 1e19
but adding 1 and 0.1 is nothing like adding 1e20 and 0.1, and that's where floats are horrible
integers have consistent precision when adding a fixed value
something like
currentHealth = Mathf.Round(Mathf.Clamp(currentHealth, 0, maxHealth));
i would just not allowe currentHealth to ever go negative
by not letting your actual health go negative
i think the idea is that this is being displayed as as percentage
i keep how things are displayed and how its in data seperated
but you should just be doing healthPercentage = ((float) health) / maxHealth and then going from there
you definitely shouldn't remember the rounded value!
and always found health as int is always better
no ambiguous situations
but you can show it to the user anyway you want
I use floats usually just to keep them contained in a single dictionary
so what do you guys think of this? iif hp s less than 0 it will be set to 0. If it’s more than max it will be set to maxHealth
as far as grouping stats goes
no accumulation problems
use a property with custom setter for HP
yes, it's reasonable to clamp your actual health value
That doesnt solve accumulation problems
but this rounded value shouldn't even be remembered
Just weighing in on what I think was the original question, and that this is the right answer to me.
For some of my games, it's helpful to have stats as ints but health as floats. They are procedural self playing rpgs, and calculating micro damage matters. But most games, int for health makes sense.
the real big-brain scheme is to not even have a difference between stats and health (:
Could use a decimal or something else sure, but in practicality it isn't much if a problem
your HP should be an int, and have a custom setter that automatically makes sure it can’t be negative
Not necessarily, there are lots of times where you may want incremental damage over time that isn't an absolute 1 or 0 though.
my HP is a ClampedReactiveValue<int>, where this is a proxy that automatically clamps an incoming value, and invokes a method when it changes
use a big int
with property to get a simpler display value
No, I think it's just inventing work tbh
it is not
using a float for HP invents work in tracking down bugs from float imprecision
don’t deal with any of that shit. use an int backing field
No, that's not a problem in 99.9% of games in practicality
a property takes extremely little effort to make. it is a core part of C#
there is no excuse to not use properties
and store a robust value that won’t cause headaches
That has nothing to do with using an int vs float
your point was that making a property invents work
That's just a process to it
it does not invent work. it is a part of using the language. the only situation where you want to store HP as a float is cookie clicker/hero clicker, where HP goes between 1 and 10^200
Well, I support you doing what you want. But this to me sounds like trying to solve an edge case you won't see by inventing work to avoid a problem that isn't going to happen in practice.
there is a reason every JRPG in the world uses discrete integer HP
because they do not want to deal with float nonsense
if you do not see the value, then do whatever. you have been warned
Yes, I don't. 🙂
btw float HP struggles to be 0% and 100%. because floats suck at ==
There are of course times where you need to change to meet an objective. But worrying about the edges of a float on a health bar for a game is (in my opinion not a problem in practice) but it is your call or whomever is making whichever
Using an int is fine, using a float is fine, using properties to pretend an int isn't an int, use it if you need it.
you only need to turn an int to a float for display bars or displaying percentages
I'm just back scrolling to make sure a question wasn't overlooked from folks
with int HP, all game logic should use integer HP and integer dmg
I definitely agree on doing good clamping in general when you need it - it's just good practice
Hi #archived-code-general are in an argument and not looking at my message so thought I'd try here before asking in advanced
I'm working on a custom package for my essential starter tools, the sorts that I can use in every project, my problem is that one of these tools needs to be customized per project and that's not easy if it's sitting in the packages directory, is there a way I can have the package place a folder with these specific assets into the assets directory? Similar to installing an exported package maybe?
heyman
actually
you can take a look at one question
if you want to
i can reference
It's pretty common to have a scriptable object or other configuration file that you generate in Assets. You could write something to do it. But I think it's really only meant to include config files.
But you can write some tooling for the package that you can right click to generate a thing that uses the package ?
@mild mortarhey buddy did you solve the issue?
Without knowing more an interface sounds like a good approach as well
I haven't actually sadly, still stuck on working it out 😅
Probably doesn't help I've been coding for hours straight so I'm actually braindead and barely functioning now
so my current jerry-rigged solution is using Assetbase to copy some of the scripts into an assets folder then using FileUtils to delete the ones remaining in packages but this doesn't seem a very good solution, I ran into the problem after I added an editor to the class and in the project I had it imported it broke due to namespaces and because the editor was still in the packages directory
so@tough lagoon you said you didnt wanted overlooked questins you can take a look at this
did you try what the fox guy told you?
this one
I haven't tried that yet, I'm just caught up on an appointment phonecall atm, so will be looking to try that soon
Would anyone know how to get an AI to move in a straight line once it spots the player without changing direction? Right now I have it set to chasing the player normally, any ideas on how to get it to only charge in a straight line?
I'm trying to use bools to get it to target the first known position, but I can't get it to work
Only set the destination once. If it's already targetting a spot, don't call SetDestination again. Only call that line whenever the enemy starts looking at the player, then set a boolean to prevent it from running again until it reaches its destination
gotcha gotcha
what is the different between velocity and force
velocity is the direction you are moving and how fast you're moving
force is the direction you are pushing and how hard you're pushing
Force, applied over time, steadily increases your velocity
Gravity is a common source of force.
AddForce really just adds to the velocity
although, you usually don't express gravity as a force, directly
Gravity's force is proportional to your mass
So you can just express gravity as an acceleration, directly
if you double your mass you double the force, and it's a wash
rigidbody.AddForce(-9.8f * Vector3.down, ForceMode.Acceleration);
Guys help
How to uniformly scale a GO ??
transform.localScale *= someSingleValue
by scaling it with same values across three different axes
I presume it's parented to something that is not uniformly scaled.
If a parent is non-uniformly scaled, then children will get skewed as they rotate
YES
That's what they said
In this case, I would suggest rearranging your player slightly
- Player
- Visual <-- non-uniformly scaled; has the mesh renderer
- Camera
- Gun Holder
- Gun
(or just parent the gun to the camera)
This way, the weapon is not parented to a non-uniformly scaled object, and everything's happy
It doesn't matter if you are non-uniformly scaled: it's about your parents
Have you tried changing the camera fov?
not really related
A super-wide FOV would definitely cause its own distortion
And without that scene view, I'd be tempted to say it is just because the FOV is wide and the gun is close
I mean, it seems that it looks fine in the editor isn't it?
pistols aren't supposed to be melted
No, it's warped there too, that's why it's not likely to be FOV
How does the model of the gun looks normally?
Can you explain each dot please ?
Each item in that list is a game object
So the hierarchy should be:
Player: Has the "player" component on it
It has two children
Visual: Has the MeshRenderer. Can be scaled however you want.
Camera: Is the camera. Has the gun as a child.
Only "Visual" is non-uniformly scaled
Everything else should just be [1, 1, 1]
(which is both uniformly scaled and the default scale)
Objects
is there a way to make a gun look at something?
Lookat rotates entire object I want to make sure its base is connected.
LookAt but with a proper pivot set up
So same look at
Could calculate a direction from the desired pivot point to the look position, the put that into Quaternion.LookRotation
I want to make sure its base is connected.
As in, you want to make sure it still appears to be held?
then yeah, just fix its pivot point
I was thinking like keeping the stock shouldered. But maybe im overthinking it
What is pivot point 😄
Make sure that your scene view is set to "Pivot", not "Center", in the top left
The pivot point is then wherever the gizmos appear.
If the pivot point is not where the weapon should pivot around, then parent the weapon to an empty object and reposition it
How to learn code
with eyes
You choose something simple that you want to do and try to do it, whenever you don't know how to continue, you search online or ask other people
And repeat with something a bit more complex each time
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!

