#💻┃code-beginner
1 messages · Page 477 of 1
How can I calculate where I need to apply a force and with what force to stop a spin?
i use jobject but jobject["thing"] magically turns into jtoken
Of which you can just keep keying into, look at the second link. What's the problem?
i specifically not used a single different object for json
everything was built on jobjects
they seem to have everything
so for example im right in the point where i want get string from, why tostring() gives me both variable name and its value
i want separate these
Instead of force maybe you want to use AddTorque and angularVelocity
yeah, sorry, torque would've been the better word. from what little i recall of physics, torque = angular acceleration * moment of inertia. how do i calculate moment of inertia in this case?
i know calculating moment of inertia is a multivariable calculus concept iirc
i know that i want to have the acceleration just be opposite the angular velocity
Yeah, would probably use AddTorque with the inverse of the current angularVelocity as the torque, and with the correct ForceMode. Maybe ForceMode.VelocityChange?
Ask in #⚛️┃physics if you can't figure it out
Worth mentioning that you can also directly modify angularVelocity if needed
yeah i'm probably going to end up setting it to 0
how do I check if not
Vector3.Distance(item1.position, item2.position) < 20
what's the opposite of less than?
in code you can check the inverse of any boolean expression with the ! operator
for example, !true is equal to false
but in this case you don't even need it
I figured out I had to do it !(...)
why though
why not just make it a greater than or equal to sign
if (!(Vector3.Distance(item1.position, item2.position) < 10))
{
Debug.Log("big distance");
}
looks ugly
ok man
inversting an entire condition looks uglier than >=?
i mean you do you but readability takes a hit there
maybe
guys, can I extract a c# code file from a builded game?
that's decompiling, which i'm pretty sure is against the rules of the server to talk about
i don't recall
is anyone here willing to hop in a DM call with me and teach me how to actually code because the youtube videos that i watch really do not help me one bit
learning to code takes years, not one call
yeah i know
what are you having trouble with?
i kinda just want to learn some of the basics
c#
c# for unity or c# in general?
c# for unity
ok so what are you having trouble with
I don't think anyone will be willing to give you a personal lesson here. If you want to know something specific, which is not to be found in your browser, consider asking your question here.
everything fr
yeah you right
speaking of c#, i gotta learn .NET, apparently that's what's big nowadays
i mean i can't teach you everything
i know
look at yt videos, if there's a concept in them u don't get, feel free to dm me
Yes, I am right. That's why use this channel for asking Unity-related question
thank you
is it convention to use var in things like enhanced for loops in c#?
i never used auto when i was learning c++
but whenever i see yt vids, everyone is using var to declare variables
I hate var, it adds nothing and takes away a lot of readability
exactly
i don't get why, in a statically typed language, you would choose to not explicitly declare the type of any given variable
Use var whenever you like. In most cases, it's used for complicated structures, which require a lot of space, like Dictionary<int, IOrderedEnumerable<string>>, so you can choose simplicity over readability if you want to
I'm with you on that one
also, why does c# have like hungarian notation sorta for its interfaces?
idk what the term would be
them prefacing their interfaces with I
I stands for Interface. This way you differentiate them from methods
Like a lot of the MS C# conventions, they are holdovers from the old C and C++ days, Totally pointless in this day and age of competent IDE's
how would you get an interface confused with a method?
ah
makes sense
As this answer suggests, just from reading what the class is derived from can tell you that's, probably, an interface
bear in mind, in the 'good' old days all we had were, literally, text editors
Hi, how can I play animations from a script?
I want to use a "Lobby Data" scriptable object to store variables like Max Players, and share this lobby data on all sorts of different objects that need it. Currently, I have the LobbyDataSO referenced in my GameManager, and made the GameManager a singleton, so that LobbyData only needs to be changed in one spot to be reflected across everything else.
Is there a better way to do this though? Should I just make a serialized private _lobbyDataSO variable in every script that needs it and drag and drop for each?
I mean you could but if its on a singleton already, why not just reference it from the singleton
Because, I think I want to do away with the singleton. Right now I'm inheriting from a base "universal" Singleton script, something I just copied off a YouTube video, and its causing some errors, I know I could fix this pretty easily but I'm also seeing an opportunity to refactor and decouple things.
Also, one day, I intend for the game to be multiplayer and have different lobbies, and different game manager's specific to each lobby - I don't know enough yet to know if the singleton will be a problem or not, but I assume so.
Does it make sense to just set up a "LobbyManager" class and then have everything else just do a "FindAnyObjectOfType<LobbyManager>" to automate referencing it? Maybe I could also define default values where needed incase of LobbyManager being null?
well scriptable object has many similiarities to singleton anyway. If its only a script needing the SO you dont need to reference the singleton of Lobby/Game Manager.
Otheriwise there is really no harm in doing LobbyManager.Singleton.SomeSettings etc.
"FindAnyObjectOfType<LobbyManager>"
you don't need this if its already a singleton
Okay, cool, I'll stick with a singleton for now then. Thanks!
Unity.Mathematics.quaternion does not have a UnityEngine.Quaternion.RotateTowards equivalent anywhere in Unity.Mathematics... right?
If I want to do incremental rotation without any overshoot towards a target value I have no choice but to "implement" that myself?
Or am I just doing something fundamentally wrong?
Quaternion.RotateTowards is a regular method from the UnityEngine namespace . . .
you can call/access it normally using Quaternion . . .
https://docs.unity3d.com/ScriptReference/Quaternion.RotateTowards.html
So is that the intended way to use Unity.Mathematics.quaternion ? every time I'm missing something I should convert it to a UnityEngine.Quaternion and convert it back again to a Unity.Mathematics.quaternion ?
That sounds wrong
oh, you're looking for a similar method within Unity.Mathematics. i'm unsure if they have one. i don't use that namespace . . .
i thought you confused using the Unity.Mathematics.quaternion namespace with the regular Quaternion . . .
Sadly not 😭
No, nothing wrong. You'll have to implement it yourself. In terms of performance, there's no difference whether you implement it yourself or Unity does.
Then you need to create your own method . . .
Fortunately, the Quaternion.RotateTowards is not an external, native function, so you can see exactly how it's implemented.
https://github.com/Unity-Technologies/UnityCsReference/blob/611307378c56a1b2f90eb1018332166cbe3c9c03/Runtime/Export/Math/Quaternion.cs#L216
Rider could
Oh, a little late about that, haha . . . 😅
I already made an adapted version of it I just wanted to know if I'm missing some intended way instead. Thanks 😄
what way do you use to combine multiple stuff in an output?
like Debug.Log("rtgrg {position} wredgrfhmewrfg")
use string interpolation
Hi, noobie here. I tried turning the child of a gameobject into a different gameobject stored within a variable. This is done in the script of the parent. I would appreciate your input!
My line of code:
gameObject.transform.Find("Item1") = Player.GetComponent<PlayerScirpt>().Item1;
This doesn't make any sense
You cannot "turn a GameObject" into another GameObject
Can you explain what you're trying to do?
Really?
Who can explain me code for random animations? I think I made a mistake and that's why I only have one animation playing
Darn, okay i guess that explains it, i can find a workaround
But a workaround for what? It's very unclear what you're attempting to do
I have a feeling your= is just backwards
It should be Item1 = Find(.. whatever)
Not the other way around
your only playing 1 animation
The child is an inventory slot that should become an item "picked up" by the player inside the player script
Random.Range(1, 2) will only pick 1 always @formal sable
you would need to use 1, 3 to get 1 or 2, it says this in the docs for it
But i think i can keep working from here. Thanks for your help
Assigning a variable is like myVariable = value
not value = myVariable
if you want to change the hierarchy (change qwhich objects are children of which) then you need to be doing someObject.transform.parent = newParent or someObject.transform.SetParent(newParent)
that's different from assigning a variable
Thank you! It's working!
maxExclusive is exclusive, so for example Random.Range(0, 10) will return a value between 0 and 9, each with approximately equal probability. heres the line from the docs so maybe you can understand it a bit better, https://docs.unity3d.com/ScriptReference/Random.Range.html
Okay... Thank you
idk what chat im supposed to go to but wehen i try to build my unity game halfway through of it building i get an error
and it dont show what errors
if it doesn't show errors how do you know there's an error?
it says it has 4 errors but not what errors
There will be other errors in the console
Are you looking at the console window?
yes
is there a way to show my errors
it says error building player 3 errors but not what im supposed to fix
most of them dont really give anything except saying something is wrong
Show them all
Ok so that's one problem. You're apparently referencing this logo in your build which shouldn't be referenced.
do i just delete the logo file?
You have to stop referencing it wherever you're referencing it
how
You have something referring to it
i started developing a few days ago
wdym they're floating around the map
those are gizmos aren't they?
idk
or is that an actual sprite
their appart of my multiplayer thing
that's not referencing the logo no
You should right cllick on the logo asset
and Find References In Scene
but also this is maybe more of a VRChat question
how
cuz i wanna test my new multiplayer build
so do u know how to fix it?
im looking for refrencses and it shows this
so they are refrences
@wintry quarry
help its stuck on this white build how do i turn it to normal
does it mean something important? (I decided to go on and don't have these stuff now)
seems your .meta isnt matching whatever you imported
i think
should not be issue unless it keeps happening
you cuold try just deleting the library folder and rebuild also
I need help. I'm trying to set up dropping items on the ground, only issue is that using triggers is not working, since there may be carpets on top of wooden/marble floors. I'm thinking Raycast's, but if the item could be constantly rotating, that will cause issues.
hey guys! so im trying to make it so that when i press space, a bullet is instantiated and is moving in the direction of my players current rotation, any tips? this is top down 2d btw
Which part of that do you not know how to do?
if you want a thicker raycast use something like a boxcast or spherecast
lmao should have specified, i cant figure out how to make it move in the rotation of my player
pass the rotation on instantiate then make bullet go transform.right or transform.up depending which way the original sprite faces( red arrow / green arrow )
but the rotation is dynamic, not just up left right or down
whats the expected way of going one step down of jtoken and reading its childs
I tried using it and just debugging whenever it hits and it seems it never calls it, any ideea why?
cs
Debug.Log(360/100);
Why does this give me 3 instead of 3.6?
JToken is abstract and may refer to anything in the JSON payload. "hello" is a JToken for example.
You need to type-check and base your logic on that. If the token is an array, loop through all its elements (which you'll get as JTokens too!). If it's an object, loop through its properties' values (which will also be JTokens)
if (tok is JArray arr)
// use 'arr' your array
else if (tok is JObject obj)
// use 'obj' your object
Integer division. Dividing two int produces an int. Make one of them a float by using the "f" postfix: 360f / 100, you'll get a float back which will have the intended result
It gives me the same result when I try to devide it with a float
rotationAmount = 360 / NumberAmount;
RotationAmount is a float
but is NumberAmount a float or an int
360 and/or NumberAmount must be a float
It does not care about which variable you'll be putting it into
float result = 3 / 10;
Gets evaluated as:
- Compute the result of
3 / 10: it's 0 - Convert that value to a
float: still 0 - Put the value in the
resultvariable
By forcefully telling it that either operands of the division are floats, you convert to float first, then perform the division
I solved it by simply delcalring 360 as a float
rotationAmount = 360f / NumberAmount;
number Amount is a int
but it all works as intended now, thanks!
and that is why the result of the operation was an int not a float
would anyone know why the sprite isn't able to be created? I doubt it has anything to do with rounding or not being perfectly divisible, since the width works fine, but the height refuses to slice at any value other than 1. (note that the input field doesnt update when theres an error; the number of rows IS getting correctly set to 2, i have tested it)
!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.
when im tostringing jtoken im getting "thing": "value" how to get only one of these
i dont see way to go futher down
That's a property. Determine its C# type and you'll be able to get either the key or value
i mean everything in json is string isnt it
It's only shown as a string
The serializer parses the string and gives you some JTokens, which is the high-level representation of the string
so i cant even get raw string from json?
json is already a raw string
Yes you can, by using the C# types, and going through the "syntax tree"
i do have type but i dont see why would i need it when i just want .value of current jtoken
because it gives me both name and value
Tokens don't have a value because they may represent more than just a value. They could represent an array and its contents, an object and its properties
I'm lost here. I have a player animator and it is getting very confuse now that I want to add a weapon system. Is it better to put all the gun controller and animations in the tank controller script and in the player animator or should I create another animator and scripts for guns?
if they represent more how do i go step down more then
By writing a recursive method, with the type checks in it
or perhaps i did bad by writing everything in jobjects now its pain in ass to get anything out of json?
You don't seem to understand that there are multiple elements in a JSON payload
yes and i wanted pretty much universal access by thing["a"]["b"]["c"}
no arrays no anything just objects that hold more objects
Unfortunaltely that's not how the serializer works
You either recursively go through the syntax tree, or deserialize the JSON payload into C# classes you make yourself, that conform to the structure of the JSON payload
is there like any thing that allows me write data to nonexistent variables
like json
i can write but not read
You cannot write to something that does not exist
heres the code:
public void SplitSpritesheet()
{
int spriteWidth;
int spriteHeight;
spritesInSpritesheet.Clear();
spriteWidth = spritesheet.texture.width / rowsInt;
spriteHeight = spritesheet.texture.height / colsInt;
for (int i = 0; i < rowsInt * colsInt; i++)
{
Vector2 bottomLeft = new(0, spritesheet.texture.height - spriteHeight);
Vector2 topRight = new(spriteWidth, spritesheet.texture.height);
Sprite splitSprite = Sprite.Create(spritesheet.texture, new Rect(bottomLeft, topRight), new Vector2(0.5f, 0.5f));
spritesInSpritesheet.Add(splitSprite);
}
characterPreview.sprite = spritesInSpritesheet[0];
charAspectRatioFitter.aspectRatio = (float)spriteWidth / (float)spriteHeight;
}
I don't seem to be able to load your video
it should just be an mp4 recorded with obs, maybe restart your discord? idk
Works for me, try restarting
To be confirmed, but seems like an off-by-one error? Error message suggests that the bottom right point of the rect is at Y 1066, which might be 1 too many for an image that is 1066px high (where coords would go from 0 to 1065)?
i've tried subtracting 1 from the height, width, and both, but that doesn't seem to work. let me restart and then record a video
Are you sure you have checked the parameters of the Rect's (Vector2, Vector2) constructor?
OH
Since it takes position and size, not corners
i think thats the issue- yeah
yep, that fixed it
my bad!
(float, float, float, float) might be better to use in your case
(to be fair im a bit surprised that theres no overload for the construtor to take two corner points lol)
thanks for the help!
I want to make a script by which my game object can throw balls towards my bat in curve direction
Can any one help please
void OnTriggerEnter(Collider other) {
if(other.gameObject.tag == "DestroyPlayer")
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}```
why doesnt this work i put it on the player and its not reloading the scene
my player has a character controller and capsule collider
hows that change what I suggested.. ifyou pass rotation on instantiate, the object already has the proper facing direction
alright, i have another issue. i'd like to make it so that, when refreshing the TMP inputfields through this method, it doesnt trigger the functions set in the unity inspector. however, the code i have below still ends up triggering the function set in the inspector. Is there any way to fix this?
public void RefreshFields()
{
charNameInput.text = currentAnimContainer.name;
print(currentAnimContainer.name);
rowsInput.text = currentAnimContainer.spritesheetRows.ToString();
print(currentAnimContainer.spritesheetRows);
colsInput.text = currentAnimContainer.spritesheetCols.ToString();
print(currentAnimContainer.spritesheetCols);
}
Yep you have a SetTextWithoutNotify(string) method usable on the text, which will change the text without raising the event
!docs
Nope, i dint (sorry for answering so late haha)
oh okay lets see it again, I need to refresh my mind. Scrolling up didn't help remember lol
I can barely remember what i ate yesterday sorry
i can barely remember what i ate today hahah
good so we're on the same page, show setup again or something we can prob figure this out in a few minutes lol
something with bullet shooting colliding with enemy even though they shot it ?
yeah
smth
well not bullet colliding
i guess something else
or the shoot script is indirectly affecting with the character
bullet is set on trigger
affect in what way
it like pulls the player to the wall, seriously.
If you are fast enought you can get the enemy to pull you to the other wall and if you just get in enemy distance you will get pushed into any wall
yes
and i know it is the enemy because if i get the range higher it also starts pulling into the wall without even moving
is it related to the player being rigidbody?
like rigidbody controlled?
wild guess without looking at code, maybe you're grabbing the player rigidbody instead of bullet
applying force to players rb instead ?
I mean i used the bullet code you gave me
and it doesn't make a mention to the player
so i dont think so
I will see which one of the 2 scripts causes the problem
can you send both scripts and mayb a vid of whats happening ?
use links for scripts
seems that the problem is the bullet script
I think i had send it before
and i dont have video software
so i cant record
The player movement script isn't picking up where the player is. What am I missing in the code?
https://gdl.space/piwelimifo.cs
here
jesus why does a bullet need to have a reference to the player
well you have this rb = playerObject.GetComponent<Rigidbody>();
but doesnt seem to be anything so should be ok
i thought that was the problem and i changed it
stills happening
no shite, that line of coding isn't doing anything
changing/remove it wont change your current issue
https://paste.myst.rs/1vo0cyn8 heres the Draw method @rich adder if u see anything that stands out to you
a powerful website for storing and sharing text and code snippets. completely free and open source.
to me theres nothing to me thats gonna make sense why it doesnt display the BG if its docked and maximized
but it does when its undocked and maximized.. (same screen size)
and that Button error magically went away when i started lookin for it
is just happening in teh editor right?
the old GUI method should still work okay.. I just heard people shouldnt built anything runtime with it. Much better to use UI or UIToolkit
I guess the problem isn't the bullet script as i thought
since even after disabling everything it contains it stills does the same
its not unless what you sent isn't the current script
check your movement script
is it only when enemy?
probably limitation of old GUI system / dealing with also rendering the other editor windows
yes
Hi there!
I have this code for updating the rotation of a cinemachine3 camera based on the script from the unity example.
My version uses an external script(TouchField) to give me a vector2 for the x and y input from the player.
however the unity scripts returns a float that seems to be based off some kind of conditional statement but i'm not sure how to tell it x or y?
https://gdl.space/yucafotece.cpp
and a link to the unity example code below
(https://docs.unity3d.com/Packages/com.unity.cinemachine@3.0/api/Unity.Cinemachine.CinemachineInputAxisController.InitializeControllerDefaultsForAxis.html#Unity_Cinemachine_CinemachineInputAxisController_InitializeControllerDefaultsForAxis_Unity_Cinemachine_IInputAxisOwner_AxisDescriptor__Unity_Cinemachine_InputAxisControllerBase_Unity_Cinemachine_CinemachineInputAxisController_Reader__Controller_)
when does it happen particularly, also could you just use the built in windows recording with windowsKey + G
or dl OBS
OBS doesn't work for my pc
I have that function disabled because it uses too many resources
use oCam, it is for lower end pc's thats what i use
shareX is also pretty compact
tried it and it goes like 1 fps
well without seeing whats happen is hard for us to see what the issue is
what do you mean 1fps? like 1fps when you are using it or when it uploads a video?
Basically seems like it applies a force (not in script terms, or maybe) to the player, like pushing him in the complete opposite direction where he was going to the wall without being able to move for some reason even after being out of the range
if your pc cannot run oCam then im not sure what you can do
I tried using it once and the output was like 1 fps
Then you should probably not try to develop games on a potato battery
output meaning? video upload or actual usage of the app
very vague meaning "output"
Like the video after being exported
Presumably, they mean the output
in that case then you can change settings in oCam to make the fps higher
idk what the wall means in this context. What about when enemy script is disabled
if its not working as predicted you messed up somewhere
work your way back to what you did while it was still working
Well, before you sended the script to me
thing is i forgot what i had before
wdym what script ?
You sended out like 2 fixed lines
Can someone please explain to me whats the difference between a Public float and a Private float
which ones cause your script looks nothing like somethign I would send to you lol
public variables are accessible from any script with a reference. Private variables are only accessible to the script they're defined in
maybe this Rigidbody rb = Instantiate(projectile, transform.position, Quaternion.identity).GetComponent<Rigidbody>(); and even this is messed up cause i told you you can remove GetComponent if you're already spawning as RB @meager sentinel
Yeah
but i dont think so
since i added the // and stills happens
So if its public I can use it in any other script, and if its private I can only use it in ONE script? But then why dont you just not make them all private?
i dont know if i deleted something accidently
To save you from yourself
Or public
generally you should make them all private unles you really need them to be accessed else where
If a variable shouldn't be edited from another script, make it private
Oh, okay, thanks a lot! <3
look up "Encapsulation"
its one of the basic principles of OOP
That way you don't end up with stuff breaking in ways you don't expect
Nava, should i just throw this code all to the trash and try to make another AI code?
probably
i doubt its that code, did you try disabling it
I mean, i couldn't know because no bullets would be spawned
well nothing is touching the player on this script 🤷♂️
Is there any guide that serves good to make an AI?
i tried making this one myself and well, you see how that went out.
AI is very broad topic
it can range from simple follow stuff to complex algoritms/systems like GOAP
are you sure the AI script is causing this though
Hello fellas, i'm having an issue with my project and i'm afraid to ask for help in the wrong place. Do I just post my issue here?
Does your issue have to do with coding in Unity?
Yes of course 😄
then post 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
I guess, i dont want to deal with this old script anymore
i have been stuck in this for 3 months
yeah so start new, one step at time
and never use Transform/Translate to move rigidbodies
Okay, so my issue is, i have currently two scenes in my project. In one, when I create a simple square and give it a boxcollider2D, and a script just to test the OnMouseEnter() method, all happens well and I get my Debug.Log("...") message. But when I do the EXACT same thing in my other scene, the mouse is not recognized and I get no Debug.Log message. For now I only want the Square in the second scene to also recognize the mouse entering its collider.
Attached are the inspectors of both squares, and the script on both of them.
I would immensely appreciate some help, as this is stalling my entire game. Thanks so much!
I see HEHE in the console in both scenes
Shouldn't you have your console window open though?
It's not actually open afaict
Oh i just didn't clear it yet, it is not recognizing the mouse on the purple scene
That doesn't make any sense, the squares are both the same, aren't they?
Are you using the new input system or the old
I fiddled with it and I ticked the "both" option
He's using just OnMouseEnter method
my friend gets this error which doesnt let him enter the project without going into safe mode
System.NullReferenceException: Object reference not set to an instance of an object.
at ApiUpdater.MovedFromOptimizer.Program.CollectMovedFromTypeNamesFromAssembly(String assemblyPath, StreamWriter outputFile, IAPIUpdaterListener logger)
at ApiUpdater.MovedFromOptimizer.Program.RealMain(String[] args)
at ApiUpdater.MovedFromOptimizer.Program.Main(String[] args)
does anyone know a fix?
Yes, which is not supported in the new input system
Oh
OnMouseEnter is only supported in the old system. I recommend using IPointerEnterHandler either way instead, as it's more robust and supported in all input systems
seems to be some type of asset
Okay, I will learn more about it. Thanks so much! I will share if it worked as soon as I implement it
It seems his Unity's APIs updater is failling
No idea how to fix it though
ah
probably a bad asset causing it
does your friend by any chance, have some very long names or special chars in their project path?
Hey guys, im VERY new to the whole coding aspect of unity, and wanted to make a NavMesh Agent go from one point to another, and when it reaches the end, it gets Destroyed. I attempted it and got an error stating the following:
error CS1061: 'GameObject' does not contain a definition for 'collision' and no accessible extension method 'collision' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
and
error CS1501: No overload for method 'Destroy' takes 0 arguments
The script is shown below
Any way around this?
Where are you getting this "Enemy.collision" thing from
you made that up
there is no such thing called "collision" on a GameObject, which is what your error is telling you.
well you would use Oncollisionenter
not just any random "collision"
also !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Also Enemy.Destroy() is likewise nonsense, GameObject doesn't have a Destroy() method
in this case - Destroy(Enemy);
best configure that ide 😅
ah, i see. apologies this is my first time giving this a shot, and i decided to wing it. thanks for the help though 🙏
you know when you configured it correctly when it starts to roast you
You would probably be better off following some tutorials to get the hang of things. And definitely get your IDE configured.
will do 🙏
yeah you dont want to just wing it without a base foundation
likewise the whole agent.GetComponent<NavMeshAgent>() line doesn't do anything and is pointless.
its YELLING AT ME !
1000% configure that ide, I know it sounds like we are harping at you but we are trying to help 😅
it can bark sometimes, we all know that pain
or choose not to update because its stuck in a loop saying "close vs" and then updater opens again and again "close vs" 🥲
oh no dont worry at all, i appreciate your guys' help fully 
if you have issues configuring the editor dont hesitate to ask, sometimes VSC can be trickier than VS to configure
got an issue again. The script works perfectly, except for the part where its meant to collide with an objcet tagged endofpath. when it moves to it, it treats it as if it doesnt have a collider at all, and just goes through it
does it have IsTrigger checked? or are you moving by not using physics aka teleporting
doesnt have IsTrigger checked, and its using a NavMeshAgent to get from one point to another. What i did was set the waypoint behind the object that is meant to destroy it thinking it would destroy the object just before it finished its path
navmesh agents dont collide with anything
they're using a mesh to navigate, their transform is written by component
shoot, that explains that then
i tie a rigidbody to mine to use for collisions and stuff
turn off gravity and stuff and and let it just follow the agent
alright, ill give this a shot
lock it or make it kinematic
didnt seem to do anything 🤔
putting a rigidbody wont do anything except give you OnCollision and OnTrigger method depending on collider type
the transform is still being " teleported "
Im trying to have it setup so that when upper is assigned, instead of having to specify which part of the enum i want to reference, having to have a seperate line of code for each instance, that i could potentially have it setup to where i can put a variable such as an integer where [ManageSkillTree.WeaponDataType.Gun] is, so that i could change the variable to call a different instance instead of having to have a million very similar lines of code.
what are you trying to do exactly? whats the end mechanic for this
for the record, this is my first time using an enum like this so if theres a really simple workaround like that that ive missed its completely on me
pretty much, im attempting to make a tower defense project, just to test out different things, and this is pretty much for the enemy getting from the start of the path to the end, then it despawns
what does collider needed for though
if you want it to stop somewhere you SetDestination to it
or agent.Stop
to collide with the end of the path, then despawn. theres going to be alot of these spawning in depending on the round, so i want it to collide with the end then depsawn for lag purposes
In my head it would work smthing like this but i havent been able to find a way
why dont you just use Agent.remainingDistance or Vector3.Distance
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-remainingDistance.html
or
https://docs.unity3d.com/ScriptReference/Vector3.Distance.html
despawn when close to threshold you assign
didnt really think about that actually. this was just what i originally had in mind. it works just fine now since i unchecked the kinematic option, so i got that working
im sure you can do this, im just thinking of how
bear with me
it goes from start to finish, then despawns. at the minute theres no issues with it at all
you care about performance putting a rigidbody on a nevmesh agent is not performant at all (esp dynamic one since they're figting for control of position)..also wait till you spawn a bunch
yeah it seems like it should be simple but i have no clue how 😭
anyway, for the rigidbody method to work like that
it needs to be a child of the navmeshagent.. (locking it in the x, y, z position [the local position])
now the rigidbody gets moved around b/c the navmesh is moving around..
then your detection logic would check against that rigidbody (the now child object) and not the actual navmesh agent
that said, Navarone's method is better for this.. if the only goal you have is to despawn them when they reach the end of the line
you could check distance.. once distance between you and the destination is low enough (you've made it -> despawn/destroy it)
simplify it
ahh i get it now, alright. once again, this is my first attempt at this kind of stuff, so im pretty new to all of this. apologies if my issues seem a bit stupid or anything
no worries.. gotta learn somehow.
i mean you can do this
private void Weapontypes(){
Zero = Weapondatatype.Gun;
One = Weapondatatype.sniper;
Two = Weapondatatype.shotgun;
etc
}
you wouldnt need an enum if you do it this way if you just put your weapon code in here
my favorite way is experimenting
which is exactly what im doing at the minute. its honestly pretty fun to be completely honest 😅
issue with doing it this way is that the enum has already been implemented into (and worked well with) a bunch of other systems in the game to the point where it would be a nightmare to change
you can use the code i provided if you have said enum already implemented
i have a way around the issue, but its brought up another issue in the way
what are you trying to do?
This @cosmic dagger
if i want to return something that isnt a simple value, what would i have to put as the identifier / where the underscores are?
still confusing what you're asking tbh as I have no clue how this system supposed to work
maybe T ? idk what is not a simple value
object ?
everything is a type. if you don't know the specific type, then you'd use a BaseType or a generic T instead . . .
Well T isnt working..... neither did object
look up generics
@hasty tundra it's hard to say anything else because we don't know what data you're trying to return or what you're actually doing (at the moment) . . .
that's not how you use it . . .
yeah no i got that now i goofed that 😭
let me try and explain it a bit better one sec
smart
well, what type does MST.Skills[ManageSkillTree.WeaponType.Gun]; return?
private T CheckTower<T>() btw
but we still need to know more
CheckTower doesn't sound like it would returns smth . . .
yeah confusing name for its current purpose
hmm, i guess it could, if it was a bool . . .
yea i was about to say.. i have many CheckInstance() that returns bools
I always prefer prefixing my bools with Is
private void CheckInstance(object instance,string instanceName)
{
if(instance == null)
Dbug.Error($"Check{currentSector} - {instanceName} is missing! Unable to proceed.");
}``` nvm im a liar.. its a void
or has if Im checking for something although usually that returns an object with an out
i can see returning a bool with an out param, but i would prefix Is, Has, or Can . . .
same . . .
i bet you i have a CheckSomething in my code base. i wouldn't be surprised . . .
wouldn't a dictionary be easier?
wait nvm nvm
what does that object returned
still reading, but what is Upg?
it literally means nothing, its just a filler name for the voids as i was typing i out for the example
doesnt mean Upgrade?
*methods not voids lol
it would in context but all i mean is you COULD change out the names for anything
so upper is set to a skill from the Skills dictionary using the ManageSkillTree.WeaponDataType enum as a key, right?
but instead, you want to pass in an int, like in WeaponUpg and use that as the key? is this correct?
basicly yeah, but dont worry anymore, ive found a workaround that works just as well 👍
all you have to do is assign a number to each value in your enum and cast the enum to an int (when used as the parameter), then change the dictionary key type from ManageSkillTree.WeaponDataType to int . . .
an enum is just readable ints. you can cast them to their integer equivalent . . .
Is this the best way to declare a singleton using monobehaviour? Is there a better way? ```public class Foo : MonoBehaviour
{
public static Foo instance { get; set; }
private void Awake()
{
if (instance != null && instance != this)
{
Destroy(instance);
}
else
{
instance = this;
}
}
}```
I personally prefer this way, then you just inherit it like Foo : SingletonBehaviour<Foo> and it has all the setup (and even lazy-loads if you want that behavior), and other objects cannot modify the Instance property
is there a way to do a "planecast" in 3d unity?
depends on your definition of a planecast
like a 2d plane
is box not a plane with 0 height-ish
yeah but from what i've seen boxcast doesn't ask forr all of the measuments in the 3 directions
it asks for the center of the box and the half extents
yes, and?
it doens't ask for the depth longness or wideness
what do you think the half extents are?
make a new vector3 with half the measurements
That's pretty clean
oh wait i'm stupid, i tought it was just a float for half extend and not a vector3
so sorry
btw there is also OverlapBox if you want a more stationary instead of needing direction or raycast hit point, just colliders (use non-alloc version)
learned the hardway never good idea to code tired
im trying out the new input system and the docs say to do " moveAction = InputSystem.actions.FindAction("Move"); " however there is no definition for actions in InputSystem
i only know one way to use it :\
thanks i diddnt think there would be one for that in particular
yeah cause its so complex 😅
at first.. they have like 3-4 different ways to get inputs
I would suggest just using the Player Input asset
then the OnMove for example from your Move action
i am used to the original input method but id like my game to be on lots of platforms
the player input asset?
https://docs.unity3d.com/Packages/com.unity.inputsystem@0.9/manual/ActionAssets.html#using-action-assets-with-playerinput
i find this easier to work with
i dont know about it
all you do is plop that component on your gameobject
use a script to use any of the messages displayed at bottom
so if you have a Move action, this componnet automatically calls OnMove method in your script when move keys are pressed
yeah Imo much easier than using weird strings n shit
how would I attach an inventory ui to the front face of a simple 3d object like say a cube or to something a bit trickier like the screen of a tablet and be able to bring it out or put it away at the press of a key or button like say tab on a keyboard or circle on a playstation controller
eith work with Screenspace and use World To Screen or World canvas
how can I make the gun lock in one of the enemy's colliders?
I tried to use a weakpoint Layer in the collider but is not working
show current code
i have this code in my editor script:
private void OnSceneGUI()
{
Debug.Log(Event.current.type);
if(Event.current.type != EventType.Repaint)
return;
var asset = target as AreaBlueprint;
DrawUtility.Draw(asset.Perimeter, Color.white, 5);
}
but i never get any logs, when does this actually get called?
how do you calculate the shoot forward for shootOrigin.forward
there is a gameobject in the player's hand assigned in the script
and the hand is pointing only where rotation of the player occurs?
yes
use a script that references the shootOrigin and do something like shootOrigin.transform.LookAt(target.collider.bounds.center)
(you would need two rays, one that finds target while you point and another for the actual shoot
that should fix your shootpoint
does OnSceneGUI not work for scriptable objects? thats my only guess for why its not working atm
idk if the collider is using the layer correctly
I put include layer
but nothing changes
yeh it is in an editor script but its an editor script for a scriptable object
it doesnt seem to execute for them
maybe because SOs are not considered "in the scene" but then not sure how you draw gizmos to debug data in a SO
i have no idea what that does tbh thats new
maybe it needs higher priority
put the debug stuff in the mb / editor only script, and access the SO like that
Anyone know why vsstudio isn't showing me unity stuff as auto complete
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Is it common/will work to put multiple short scripts on one player? Like "playerMovement" and "playerCollisions"? Or will that cause issues?
why would it cause issues
and most cases ideal to do so, split different purposes into seperate script
I was thinking maybe calling start and update 2 times on the same object might cause issues. No real reason to back up that thought but still was a thought, thanks for the clarity tho!
So I have a question regarding procedural generation so I want to make levels to be procedurally generated much like rouge like games but I don't know how to go about it like which algorithms to use the next problem is that I want to pass a list of premade rooms that can be placed randomly through and the those will be connected through corridors and lastly I want to define like a exact section for the spawn and the boss room are or alternatively I want a set numbers of rooms that must exist in between the boss and the spawn room
Any form of help is appreciated like videos or forums
how do i add a fire rate to my script? im kinda new and this is for a school project that is due tomorrow. Pls help
there are plenty of examples on google
no I will not send you the link to something you can easily do on your own as shown above
what kinda lazy bum question is that
im at school and the internet blocks stackoverflow, can you sent a screenshot?
break your task to more comprehensible tasks, like
- detect mouse button (I see that you've done this already)
- check if timer is zero
- if timer is equal or less than zero, shoot (you've already done the shooting), then set timer to the amount of delay
- else, decrease timer by Time.deltaTime
k thx
if you put effort and looked for a second at the images, would've seen there is one of the code examples...
i did look, im just new so i didnt realy understand it
I had to change from layer method to make the script get the collider directly from the enemy game object. The problem is that it’s only identifying the first collider, and no matter what I do it don’t recognize the second
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Having lots of Updates can affect framerate, but it heavily depends on what those Update calls are doing, and Start may only cause conflicts with race conditions in your logic, since the order of Start is not predictable, you may not be able to have code in your collision script for example reference something in your movement script, if your movement script also needs to initialize the thing your collision script wants to reference that early - though Game Objects in Unity are entirely designed to have multiple scripts on them working independently, so as long as you handle your logic and understand the execution order of scripts, you should be fine - another option I usually do, is have scripts use a System.Serializable attribute and not inherit anything, then 1 MonoBehaviour can call a "OnUpdate" (or however youd prefer to name your functions), this way 1 Update can run the logic for multiple scripts
This sounds like a strange oversight on your schools part, im guessing this assignment is code related to your course, so its odd your school would block a code related website - although StackOverflow is not the only place to find examples, theres also the Unity Forums and many other blogs online, and the official Unity Docs which do have examples on using coroutines as its part of their API
its likely a highschool, its pretty common for them to just blanket ban anything. Or it could even just be a whitelist of allowed websites, which would be worse for them
Owow, I guess my highschool had it light, only the explicit NSFW sites and gaming sites like miniclip were banned
what does first and second mean in this context?
show code
i mean its already good enough, our school banned all method or tricks that are not taught from the lesson
even if u can do the work, if its not taught by school , 0 mark
tbh idk what order he is considering
but in this case he is considering the bottom collider
(the bottom in the game, the first in the inspector)
ok, I kind of figured it out
he is using collider index to list the number of colliders in the game object
these collider sections should all be their own gameobjects
Hi. I'm trying to write a function to add to a Button.clickable.clicked and pass in a variable. This is in the Awake() of a script attached to a UI uxml
When I pass an arguement in I get "Cannot implicitly convert type 'void' to 'System.Action'"
playerTabButton0 = rootElement.Q<Button>("player0Tab");
playerTabButton0.clickable.clicked += showPlayerProperties(0);
private void showPlayerProperties0(int playerId)
{
GameStateScript GameState = board.GetComponent<GameStateScript>();
GameObject player = GameState.playerList[playerId];
}
How can I pass an argument into this function?
Hello I was having a lighting issue where when I switch from my main menu scene to my game scene the lighting bakes itself and everything goes really dark is anyone able to help me out with this, I dont really know what I am doing.
...clicked += (id) => showPlayerProperties(id);``` Assuming the button click event takes an integer.
if the button used an int, it would pass it as a parameter already
if you need to unsubscribe this method eventually, then you'll have to create a new method which takes no parameters and calls showPlayerProperties(0);
then just subscribe it with playerTabButton0.clickable.clicked += myMethod;
otherwise you can use the lambda syntax like
playerTabButton0.clickable.clicked += () => showPlayerProperties(0);
Where would this button int come from? And how would I access it in the function?
it doesnt, i was saying that the above code wouldnt be neccessary if the button already passed an int as the parameter.
I've now got this problem. I have 4 buttons that each call the function with different player ids. When I click button 1 it prints 4 times with the id of each button
playerTabButton0 = rootElement.Q<Button>("player0Tab");
playerTabButton0.clickable.clicked += () => showPlayerProperties(0);
playerTabButton1 = rootElement.Q<Button>("player0Tab");
playerTabButton1.clickable.clicked += () => showPlayerProperties(1);
playerTabButton2 = rootElement.Q<Button>("player0Tab");
playerTabButton2.clickable.clicked += () => showPlayerProperties(2);
playerTabButton3 = rootElement.Q<Button>("player0Tab");
playerTabButton3.clickable.clicked += () => showPlayerProperties(3);
}
private void showPlayerProperties(int playerId)
{
print(playerId);
}
When I click any of the other 3 buttons it doesnt print anything
Duh
Its querying only the first button
So I have a question regarding procedural generation so I want to make levels to be procedurally generated much like rouge like games but I don't know how to go about it like which algorithms to use the next problem is that I want to pass a list of premade rooms that can be placed randomly through and the those will be connected through corridors and lastly I want to define like a exact section for the spawn and the boss room are or alternatively I want a set numbers of rooms that must exist in between the boss and the spawn room
Not really a code question, you might be better asking in #archived-game-design
Having said that Proc Gen is most definitely not a beginner topic but I would suggest you start by researching Maze algorithms and try to implement some then take it from there
Doesn't procedural generation use algorithms?
Everything uses algorithms, proc gen is generally based on one of the common maze algorithms unless you design your own
I will look in to maze algorithms as well thanks
Ohhhh
Presumably it's in a folder called Editor, or it's under an Assembly Definition marked as Editor-only
But looking again your class is generic, you can't add generic classes directly to GameObjects; the error is just confusing if that's what's causing it
you can have a generic base class, but to serialize them in the editor you need to have the derived class strongly typed
otherwise start digging into serialize references
i see
https://gdl.space/bizawucivi.cs how to call a method when building? I want this specific script to destroy all of it's type on compilation
"AGHHHH".log(); Why are you making these awful extension methods 
Anyway does this not work? It should https://docs.unity3d.com/ScriptReference/Build.IPreprocessBuildWithReport.OnPreprocessBuild.html
Does it call the method at all?
Does it call the method at all?
I had an old method ipreposscess thing that workdd in 2017, howecer that was deprecated and unity told me to use this instead
Does it call the method at all? 
i wouldnt ask if it is
So the issue is that it's not destroying anything?
yea
Can you put a break point in the loop and see if there is anything even being destroyed?
And if so, what does it think it is?
Maybe this? https://stackoverflow.com/a/76635848
Also, verify it's actually not called by doing something that actually changes something visually
lemme see, that would be dumb to set true by default
Logs might get cleared
so that's what killing the logs, dont make sense to defineit true by default
It's probably there for a reason
let me see if it actually destroys the things
For now I'd check if it calls the method at all
I see.. it is only being called once, only deleting active objects on my main menu, instead of each scene 🤮
@wheat wave it doesnt require a parameter, this is the whole code
@faint lark why are you even using ToArray in the first place? it seems that r_33_list is already a list<int>, which the left side expects
ok?
i didnt write this code, i simply imported the package and i got these errors
removing the .ToArray and see if it works
did you message the original author?
no
it seems that removing toarray removes the error
dunno if wuld brake its functionality
that's a question for the asset creator
yeah i guess your right
What asset is that anyway?
Either it's a very old code or a plain mistake in the code.
How would this break exactly?
You create a new collection which is accepted in the field/property. Unless you modify the list after this nothing will break that you caused
If that field/property is of a library then the author is the one who made the mistake considering they want you to pass a hard list type rather than a general interface
Nevermind, I would guess this is some tile based system and the point is to add/remove parts of the list. Regardless there should be an easier way to set this list.
Can some one help me with codeing a weed growing system and planting
what in particular do you need help with
those are pretty large systems
Oh
what specifically do you need help with?
Just the whole thing
well that doesn't give me much to work with, the only way i could help you with the "whole thing" is telling you exactly how you'd make a planting/weed growing system instruction by instruction
are you not sure on where to start?
Yea I’m new lol sorry
I’d make a plant pot that is the perant of the weed plant and as it grows it scales and you need to water it so it would have to have a watering plant and a seed bag that holds 10 seeds and it needs a uv light so it would grow
But idk how to do that lol
okay so
a seed bag that holds 10 seeds? are you making an inventory system?
because that's what it sounds like you're going to need
Yea I have the ui done
okay so you need help making an inventory then
my reccomendation would be create a scriptableobject of inventory items
and use whatever data structure you want to store
Ok
hi i am trying to make my bullets speed up when i press e and it is not working the bullets are prefabs and don't actually exist in the scene until i spawn them in from another script here is the code: https://gdl.space/oliruzegir.cpp
upon further inspection if i press e while the bullet has been spawned the code works
but i need it to work before it is spawned
Why is there a delay when I press the LMB while running to make a hit? Can this be fixed?
I have unchecked "Has exit time" and the animation is broken
I tried to set the transition duration to 0.1, it didn't help... At the moment I was clicking on LMB, and as you can see, the animation is not working
so you need to capture the key in the spawning code and maintain a speed variable there. then when you spawn you can set the speed variable of the bullet immediatly
Then it certainly shouldn't be based on code on the bullet itself
The bullet script should get its speed from elsewhere, a script that always exists
A Singleton may be a good option for you
Anyone got tips for me to get back into this game engine. i really wanna get back into this but i forgot scripting like everything. i used to code 2 years ago but took a massive break.
Or just having the spawner set the speed
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Quick question: If I want to make a group of functions globally accessible or accessible at my discretion without inheritance, is that when I should use an interface?
no, you would use a static class or implement the singleton pattern
Wdym by "globally accessible"?
public static
Just a class that I can call from anywhere without messing with inheritance
I've been reading up on static classes since the first reply
An interface is when you want to force classes to have a certain implementation. For example, ICloneable forces it to have the Clone function. That way you can have classes with certain implementations without establishing a relationship
Specifically I'm making an in-cutscene manager and I want to programmatically trigger events like "walk to location" or "trigger inputted dialogue box" using parameters
Then I realized it'd be useful for other situations that'll appear, and so I don't have to connect a bunch of scripts
Just be careful with them. Singletons can cause major problems if used incorrectly,
so most people avoid them.
It mostly comes to expanding your project though.
I was asking HT what THEY meant by it.
Note the difference between an actual static class and a static reference to a singleton instance. They are different.
Yeah. They can run into similar problems though
"most people avoid singletons" is definitely not true lol. It's extremely popular, and useful.
I know that singletons have their haters at least
Guys, can you help me? I don't understand...
Seems like more of an #🏃┃animation question than a code question
Here is an article :)
https://gameprogrammingpatterns.com/singleton.html
Tells you why they are controversial
They are convenient but if used incorrectly can be devastating. Though if it is a simple project, you’ll be fine
They aren't controversial, people just sometimes abuse them in weird ways.
Every single tool can be described this way. They're a tool.
Also depending on the api, you have no choice but to use singletons/static hell
(such as a lot of editor tooling)
That article is frankly rubbish in a Unity context, for one thing it misses the point that a Singleton in Unity is serializable in the Editor and editable via the Inspector. Those are really the only reasons to use a Singleton over a static class
After a bit of reading, I think I might only need a static class over a singleton
I just need some simple implementation of functions, and I don't really want the script coupling
I will probably need to learn singleton design pattern at some point though
Nah. You can subclass singletons
but why would you, that is definitly the road to Singleton hell
You can also have a singleton descend from monobehavior
Variety of reasons, but the one they gibe as an example is having different operations for different platforms
That is hardly specific to the Singleton pattern, abstract classes and interfaces deal with that situation very nicely
Well, if you want it to be globally accessible, but yes, you are correct
Realistically, if Unity serialized and made editable static classes 99.99% of people here would never even have heard of the Singleton pattern. It is a solution of necessity not of choice
I think Odin has a window for that 
They do
instead of the ScriptableObject architecture for representing individual values/data, just create a Singleton architecture where each data type is its own singleton. then you can access any variable from an instance, anywhere, yay! 😆
I wouldn't say that folks necessarily hate it but it goes against a lot of programming concepts outside of game development. It's perfectly fine for game development with Unity though.
Totally not me using multiple architectures erroneously
Even better: Make a static class with a method that runs an if / else / if logic until it obtains the data it wants.
The Yandev way
Was about to say-
Kind of unfortunate that game. I had heard that he had actually gotten a lot better with criticism and fixing his code until all the stuff happened
I'm aware this will sound like an incredibly stupid question but how do I get the correct local(?) rotation of a specific GameObject? localRotation isn't what I'm looking for since the GameObject I'm checking is the main parent.
My issue is that if I set another GameObjects rotation to the original, I'm seemingly either rotated relative to world space or incorrectly rotated. This is all I'm doing for it.
public void Teleport (GameObject target); // Custom function to teleport the player
{
Player.gameObject.transform.position = target.transform.position + target.transform.forward * 0.3f;
Player.gameObject.transform.rotation = target.transform.rotation;
}```
It's anything from perfect rotation to 180 degrees off, the position works just fine.
wdym checking?
Also why not just
Player.gameObject.transform.forward = target.transform.forward;
Hello! How could i extract from a json file an array of classes
This is the json file:
{
"Aaliyah Gray": {
"pfpImageIndex": 10,
"score": 7450
},
"Aaron Price": {
"pfpImageIndex": 8,
"score": 8175
},
"Abigail Baker": {
"pfpImageIndex": 3,
"score": 9600
},
"Adam Barnes": {
"pfpImageIndex": 1,
"score": 8125
}
}
and this is the script:
using System.Collections;
using System.Linq;
using UnityEngine;
[System.Serializable]
public class User
{
public int pfpImageIndex, score;
}
public class DataSaver : MonoBehaviour
{
public void LoadLeaderboardsDataFirebase(string jsonData)
{
if (jsonData == null)
{
Debug.Log($"No data found");
return;
}
User[] users = JsonUtility.FromJson<User>(jsonData)); // ik its wrong but how can i make it work
}
}
you would need another class that contained a User array and serialize/deserialize that class
I want the 30cm offset. I should've added a negative value but it's for teleporting behind an enemy.
By checking I guess I just mean setting one rotation to another
The question doesn't make sense to me. What I think you're most likely seeing is that Player has a different pivot than the target. That is, what you consider to be the zero rotation for the player is not the same for the target.
what has a 30cm offset got to do with rotation
transform.rotation is always the correct world rotation. Setting it to another transform's rotation will always set it to exactly the same.
That's for the position
position + forward * -0.3
so why mention it? My code is setting the rotation by setting the forward direction of player to target
because I just copied it from the code directly
I don't feel like that's a big deal lol
You misunderstood Steve's suggestion as something related to the position, because it also uses transform.forward, but he was suggesting as an alternative to setting the rotation
Because setting transform.forward will change the transform's rotation.
JsonUtility doesn't support naked arrays.
Ah, ok, shouldn't target.transform.position + target.transform.forward * 0.3f set the rotation at the same time then? that's even weirder since they should be the same.
no
No, because you're just reading transform.forward there, not setting it.
Ah that makes sense, I'll try a combo of layouts, I'm just thinking about what would and wouldn't break with Player.gameObject.transform.forward = target.transform.forward * -0.3f
that makes no sense
As PraetorBlue said, the Unity JSONUtility does not support naked arrays. You can use another json deserializer like the Newsoft package
private void Update()
{
playerDetected = Physics2D.OverlapBox(doorPos.position, new Vector2(width, height), 0, whatIsPlayer);
if (playerDetected == true)
{
Debug.Log("Space Passed.");
if (Input.GetKey(KeyCode.Space))
{
Debug.Log("Key pressed.");
GameObject player = GameObject.Find("Poppy");
if (player != null)
{
Transform player_transform = player.GetComponent<Transform>();
if (player_transform != null)
{
animator.Play("SceneFadeStart");
StartCoroutine(Wait());
player_transform.position = new Vector3(3.5f, 26, 3);
}
}
}
}
}
IEnumerator Wait()
{
yield return new WaitForSeconds(1f);
}```
I'm trying to make a screen fade before the player moves location. However, the player moves instantly just as the fade start. I can't seem to get the Wait() method to work. What am I doing wrong?
Would you like to elaborate or just tell me it makes no sense? You did the exact same thing bar * -0.3f 🫠
you need to put your player teleportation in the IEnumerator
forward is a direction vector so multiplying it by anything only changes the magnitude not the direction it represents
youre calling the wait and ur player position at the same time
Put the line after wait inside the wait function after yield
You're misunderstanding what transform.forward is representing there. It's a normalized direction. Multiplying it by -0.3f will make it point in the opposite direction and scale it down to 0.3. transform.forward will just normalize it anyway, it doesn't care what the length of it is.
I will try that. Thanks for the help!
Coroutines don’t work like wait functions in threads.
The suggestion is to make the Player's forward direction match that of the target's. This is effectively the same as setting the rotation, except it will only ensure the Z (forward) axis matches, and then try to make the Y (up) axis point up as close as possible without changing the forward direction.
So, just to humor myself, would a mix of something like this work?
Player.gameObject.transform.forward = target.transform.forward;
Player.gameObject.transform.position = target.transform.position + target.transform.forward * -0.3f;```
That seems like it would provide the best of both sides together
If that's hugely wrong I promise I'm not intentionally ignoring/disregarding any info, vectors just confuse me 😄
I don't think it will fix your problem, because there's fundamentally nothing wrong with setting transform.rotation to match another transform's rotation. If it's not giving you the rotation you expect, then that means one of the axes do not match what you expect.
This is the correct way to implement that suggestion, yes.
Is target an empty transform? Are you placing it manually in the editor and rotating it, using just the transform arrows as reference?
Hi I’m thinking on taking a course or trying to learn c# dose anybody have any suggestions
target is the closest enemy relative to the Players transform, I'm using the arrows as a reference since forwards is always the direction enemies face
That shouldn't be able to change, which is why I'm really curious why it's giving me a weird behaviour
read/learn from a website or online videos from youtube before paying/taking a course . . .
Ok thanks
There's nothing wrong with the math, so it has to be the rotations you are working with. Can you show exactly how the rotations are wrong, with your original implementation of setting transform.rotation?
If you look at both transforms in the scene view after the teleport, with Local handle rotation set, are you seeing the transform's arrows not matching?
what is the savesystem used by the cinemachine called? The one that retains changes from runtime
I didn’t know cinemachine had a save system but it is likely player prefs
nah, they're talking about how cinemachine has a toggle to keep/persists your changes after play mode exits . . .
Oh
i was just looking at it, but now i'm completely blanking . . .
Then no, that isn’t player prefs lol
use the [SaveDuringPlay] attribute on your classes, and the [NoSaveDuringPlay] attribute on fields to exclude them . . .
yeah, it's pretty dope . . .
I don't get why my player won't move in any direction. It was working before, I didn't touch the code but when I go back to it, the player won't move again.
okay well not much we can do from that statement alone
at minimum show code, also screenshot console window clearly visible during playmode
hi guys! working on a dialogue manager script and i was thinking, should i force code every "peculiar dialogue" in the game? as each dialogue will be weird in its won way, some having camera movements, screen fades and such.
what is " every "peculiar dialogue" i"
this screenshot in playmode when you cannot move?
Right
Im not seeing any debug logs in your scripts, that should be your first step
find out which script is running and which one isn't, debug some values like bools you have or any input floats
It's in the PlayerMovement script. It's not picking up if the player is moving or not or displaying their destination
where did you put log? also did you check MoveRoutine ?
I haven't used a debug log. I was checking when running the game when I tried moving that the isMoving wasn't checked and that destinationPos doesn't pick up the player's location when changed. What about the MoveRoutine?
wdym what about MoveRoutine.
Check if its hitting it at all
start using logs
It isn't
well that explains why its not moving then, find out why the corouttine isn't calling
dialogues where the camera moves in a certain way, where it loads a diffrent scene to show it, where the screen fades or shakes (its a 2d game)
What should I put in the Debug log in the Coroutine?
well first put the log before StartCoroutine, then put it inside coroutine when it starts and then another at the end
Ok
I would look into using something like Timeline
what's the advantage of timelines vs hardscripting everything with timers?
ofc clarity and order, a messy project wont go anywhere
tysm
I have an object that whenever I start the scene my objects moves from where Inset the transform but I have no code or anything moving it, is there a way to fix this?
prob external code is moving it, else it wouldnt make any sense
Guys I need some help, I'm working on a timer UI and here is the code I wrote for the UI.
The code is fine but the UI is shaking when the millisecond updating
should format it to only show soo many decimals..
and when those are 0, fill em in with 00
22.00
22.01
22.11 etc
and using a monospaced font helps
They're doing it with the string.Format. So yep it's probably the non-monospace font
yup, cant beat a good monospaced font where everything stays in line
There are no decimals, milliseconds is an int
And it will already use at least 2 characters due to the :00 format specifier
if all thats true then the twitching probably is because for example 01 is shorter than 00 soo ur seeing a flicker.. use a monospaced font
im trying to limit the speed of my player by adding an opposite force once he reaches the move speed
but it isnt working correctly
any better way of doing this?
maybe use drag
Yea it works after I change the font. Thanks guys
rb.AddForce(transform.forward * forceAmount, ForceMode.Impulse);
//speed limiter
if (rb.velocity.magnitude > maxSpeed)
{
rb.velocity = rb.velocity.normalized * maxSpeed;
}```
i cant set the velocity
i need it to be fully physics controlled
i cant directly manipulate the velocity
ohh <insert more math then>
void ApplyForceWithLimiter()
{
float currentSpeed = rb.velocity.magnitude;
if (currentSpeed < maxSpeed)
{
float speedDifference = maxSpeed - currentSpeed;
float adjustedForce = forceAmount * (speedDifference / maxSpeed);
rb.AddForce(transform.forward * adjustedForce, ForceMode.Impulse);
}
}``` something like this then perhaps
i need to limit speed but also allow force being added, so i want to suddenly add a lot of force to push player to the side
then the speed limit wouldnt stop that force
my code above wouldn't stop any force just scale it the closer to the max speed the objects moving..
soo forces would work as normal unless ur already at or close tomaxSpeed
The Debugs aren't picking up anything for some reason
cutting the input away at max speed would work but at the same time its a bad way
Sounds like you want exactly what the speed limits feature of BetterPhysics does:
https://www.youtube.com/watch?v=dRtHHhhKUn4
https://assetstore.unity.com/packages/tools/physics/betterphysics-244370
any way to do it without spending $20
sounds like the coroutine is not running
in my ApplyMovement i want to have an acceleration variable which is just how fast the player will build up speed
and in my CounterMovement i need to somehow limit the velocity to moveSpeed
whilst still allowing other forces to act on my player letting him to go beyond moveSpeed
as it was on the video u sent
why cant i rename these materials?
Not a code question! If these are under an imported 3D model, they are bound to the model and cannot be renamed
oh ok
https://paste.myst.rs/pirsidze something like this should work
- first deal w/ movement directly from input
- predict/project if the rigidbody will exceed speedLimit
- scale if it does (so movement wont exceed it)
- now anything else we can exceed that limit (only applies to input movement)
a powerful website for storing and sharing text and code snippets. completely free and open source.
can rename in the 3d package you export the model from
Hey, I'm trying to get a tree to spawn after i place down a sapling. for some reason. it always spawns so close to the mindelay. Even if i set the max to 100 and the min to 1. it'll always spawn around 1-1.5 seconds
Did you change the delays in the inspector?
You need to change it in the inspector, changing it in the code won't do anything once it's serialized on your script.
wait also - you're starting the coroutine every single frame 😱
so basically what's happening here is every frame you're starting a random delay and then whichever one finishes first will succeed
and then the script is destroyed.
You should only start the coroutine once. For example do it in Start, or do it in response to something happening in the game.
Update runs every single frame.
you are absolutely right. fml. Give me a sec
it works. just need to edit my code slightly to work with my system. Thank you
switch (true)
{
case (popualtion > 0 && popualtion < 20000):
sr.color = colors[0];
break;
case popualtion < 50000:
sr.color = colors[1];
break;
default:
sr.color = colors[0];
break;
}
Is this not possible in C#?. I am getting an error "error CS0150: A constant value is expected"
on the lines with the "case"
You want this perhaps?
looks weird but I think it should work, thanks!
which one would allocate more memory - a int[2] or a class with 2 ints
The array I would guess. Pretty sure C# arrays store a separate length field internally.
Prefer a struct with two ints if you want no allocations
The memory allocation different is so minimal that you might as well do whatever is the most convenient
which is almost certainly a class or a struct over an array, if the two numbers have different significances
can someone help me with what this means? i just followed a tutorial to do this, it was working perfectly the other day but i came back to check it again and now im getting this error
Did you read the last sentence of that message, and checked to see if that was the error?
thanks!
i also hope you realize that this guide just takes you through exactly what that last sentence of the error message is
nobody is "treating you like an idiot". but when you fail to read what is literally on your screen, it will be pointed out that the answer is literally on your screen
The regret must've kicked in fast for them after typing that.
What's actually wrong with it? I tried messing a lot with that problem and there's literally 0 fix. I want the wheelchair face to be rotated to player but it does weird stuff instead of rotating exactly like LookAt (which works but I don't need that solution because it noclips)
Quaternion wantedRotation = Quaternion.LookRotation((Player.position - transform.position).normalized); // * 6f;
Quaternion deltaRotation = Quaternion.FromToRotation(wantedRotation.eulerAngles, Player.position);
Debug.Log(deltaRotation.eulerAngles);
GetComponent<Rigidbody>().angularVelocity = deltaRotation.eulerAngles;
I have no clue what is quaterion and how it translates and no clue how to fix that problem and debug it
I tried tons of different solutions
So what programming languages does unity support?
you make scripts on it in C#
😡
there are beginner courses to learn c# in the pins if you want to get started learning. otherwise, there's the infinitely inferior #763499475641172029 or you can use a different engine that supports your language of choice
no visual scripting
i will have to learn c#
unreal engine doesn't support many languages either
nor does goDot
and the other engines aren't as powerful
godot kinda does tho
C# mainly, but a bit of javascript and python
I need to expand my skill anyway because I can't cruise through life with lua and python
Godot has community added support for a lot of langauges
what languages?
ton
unity has not supported javascript in like a decade (and it wasn't even """proper""" javascript). and python is only supported for editor stuff with the Python for Unity package
C# is industry standard anyway
GD script, C#, and C++. I know it has some for Rust. I don’t know others
Though it had more with Js, but you are write for python
so what's private and public in C#
there are community added ones as well
does unity have modules?
can I use modules that i can import/require
to organise my classes, utils, etc
C# uses namespaces yes
yes
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using UnityEngine;
again, there are beginner c# courses in the pins. start there
so unity has a player instance
they're gameobjects unlike in roblox
ohh
so we construct our own game object
so we make our own player instance
ah i see this makes sense
roblox hands everything to us, unity doesn't this is cool
gives a lot more freedom
for our data services, do we have to host our own third party cloud databases or does unity provide
you host a server, this is no pet simulator
unity gameobject = roblox Instance
There are unity services for a lot of things, not talking about databases only here, but apparently they can be costly if you expect a large scale.
yes, i know what a game object is
yeah, they're costly
does unity provide databases
no block fruit
😭
it entirely depends on your needs. there are plenty of free services available for hosting data, firebase, unity's cloud save, etc. of course there are limits to many of their free tiers, but there are free tiers available for many of those services
okay okay
there's no free game:GetService("DataStore")
brother
Well there is, it's called your filesystem
i can still host my own servers for roblox games
