#💻┃code-beginner
1 messages · Page 278 of 1
private Vector3[] directions = new Vector3[4]
{
Vector3.up, Vector3.down, Vector3.left, Vector3.right,
};
private void Awake()
{
var randomDirection = directions[Random.Range(0, directions.Length)];
}```
Make x a string
Get type returns a string with the name od the class i think
oh okay
pretty sure you can just compare types
yes but the context where I compare types, needs to be agnostic to which types are being compared
it needs to be injected in
a function that takes in a list of objects, and a type, and returns true if all objects are instances of that type
but you apparently cannot have types as paramters
functions cannot take in literal types. only instances
hmm, aight. I mean technically a lot of this reflection and type stuff is basically string lookups anyway
yeah but string lookups mean I can accidentally put in any random nonsense
i have to consciousnly do the mapping in my brain
of strings to actual classes in my codebase
that is pretty horrible.
You can do this then
bool Func<T>(List<object> items)
{
foreach (var i in items)
{
if (!(i is T))
{
return false;
}
}
return true;
}
I think
If u want it encapsulated in some class same idea
Generally, if you're using object outside of serialization you're doing something wrong
Welp this entire idea of checking if object is of some type return true and if not return false feels sus to me
Hey how do you render a mesh with textures without creating a new gameobject?
as in swapping the texture?
ud have to copy the renderers material, swap the texture on the copy, and assign the new copy back to the renderer's material
It's called direct drawing and GL does provide it, but for larger operations you'd usually use https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstanced.html
Well, instanced is good for drawing a bunch of similar meshes, but there's also DrawMesh and DrawMeshNow
No, as in render an object in the world without using any additional gameobjects
No
This supports materials? I didnt know
Will be checking it out
oh, Instanced says obsolete now so there's this one too:
https://docs.unity3d.com/ScriptReference/Graphics.RenderMesh.html
https://docs.unity3d.com/ScriptReference/Graphics.RenderMeshInstanced.html
Ah, ok right it uses those RenderParams now so DrawMesh and its friends seem obsolete
I can't tell the difference between all of the Render methods and Draw methods
And it doesnt look like the Draw methods are obsolete
Only DrawMesh, replaced by DrawMeshNow
RenderMesh has these which give more specific options to render with
https://docs.unity3d.com/ScriptReference/RenderParams.html
because if you took a look at the parameters of DrawMesh it was boarding like 10ish
to note that depending on purpose you can also use CommandBuffer or RenderFeature, it also allows you to draw anything but you can abstract it into a single post processing class
I haven't seen you for so long
you had a different name?
You helped me with a bunch of non-unity code a long time ago. Nevermind it.
hey guys general question: if i have a feature i want to implement, how do i find a good way to implement it? there are so many different ways to program things and its kind of paralyzing me right now
id like to make a spell casting system and i have the idea but i physically cant start because im having trouble deciding how to start
scope it small, make something out of it, try your shot at it again in your next project
Not his question
this isnt orthodox but i have pretty much one project that i work on
The way I always look at it is from a realistic standpoint. Try to imagine how it works (or would work) in real life, and try to model that behaviour with code.
It's not a common method, but it's helped me through years in deciding how to design a feature, and usually results in very clean and intuitive code.
What about the spell casting system confuses you?
so far its mostly how i could choose what spells to cast
i could make a system similar to an inventory hotbar where you choose them
or a wheel
but im having a bit of trouble deciding
oh if it's just a hotbar issue yeah do it like your inventory
similar concepts really
Lol okay I thought you were talking about how it should work internally.
With this, you will simply have to decide what looks best and what goes best with the game's theme.
oh and i know of the concepts of coroutines and i heard theyre good
what situations should they be used
Whenever u need to use delays or timers
I would only ever consider using them in say, cutscene or non gameplay critical scenarios.
Usually you can get by with much more performant code with other ways
float is your friend
I see no reason why a delay would ever require a coroutine
sleeping coroutines is somewhat more performative than checking each frame
Spellcasting system:
To begin casting a spell, left click the selected spell. This will begin the casting process and enable the minigame.
The minigame is a skill based reaction game. A button will appear on your screen that you must press before a timer runs out. If the timer runs out,
or you click the wrong button, you will get a strike. Getting multiple strikes will fail the spellcasting and depending on the potency and spell type there will be consequences.
Successfully clicking a button will increase the spells potency and a new button will appear. The higher the potency, the harder the minigame will be.
There is a total timer that indicates how long you have left until the spell automatically casts. You can also skip the time if you reached a desired potency pre-emptively.
The buttons will become more difficult as the potency increases.
heres my idea
what would you guys do?
such that if you do want to make a effects type of class, checking each frame can be somewhat demanding if you have like a ton of them ticking on all your enemies. It's a trade off though.
runtime performance vs object instantiation and some gc tax
gc tax?
garbage collection since coroutines do create a bit
garbage collection
ah
pooling coroutines is a thing too, but that's a little more advance
Sounds fun. I dont see how a coroutine would fit in here. A regular number timer would do fine,
yea i think that too
most people eventually switch away from unity coroutines and use Unitask/MEC or some other implementation
my gameidea also includes a bunch of procedural generation but thats a can of worms im not ready to open yet 💀
Yeah I was about to mention. The way it works in Unity is you're provided a pretty basic tool, and you can upgrade them with the asset store.
im already ovewhelming myself lmao
could you recommend some good tools in the store (preferably free)
I'm the type of person that would only consider coding a custom coroutine system. It's probably not the best way of going about things, though.
I use coroutines as a custom ticker for my ai brains 🫠
So I can't recommend any assets
ah
start with built in coroutines, get used to them then look into others, they are more advanced, Unitask is essentially a reimplementation of async in unity, so you have to learn async, and MEC https://assetstore.unity.com/packages/tools/animation/more-effective-coroutines-pro-68480 is what unity coroutines should have been, bigger api, not bound to specific mono, no gc
im still pretty much a beginner so what you just said is magic to me
stick to built in then, they are good for majority of cases
will do
@rich bluff @timber tide Update: I have no idea what I'm doing
I don't really know how to scale the thing properly, and it's only showing one material (you can see the proper look with the other bullets)
snapzones?
There is also this weird ass desync. I think that's just because I made it render in OnBeforeRender
desync maybe because you are sampling the physics controlled position, im not sure whats the fix there
Desync was due to the onbeforerender thing. I fixed it.
I make like coroutine singletons and just toss them on that, but yeah, the unity coroutines aren't the greatest. Ideally if you do want to make a bunch of coroutine logic running at once, you'd make a sorted queue and pop them off. This way you'd only need to check against the queue and not each individual coroutine.
I'm pretty sure unity does something similar under the hood, but making something like that isn't that difficult.
The big problem I do have is the gc, and that's why I do try to reuse coroutines when I can.
My actual issues are the proper scaling and multiple materials
Unitask is kinda required though if you do want to use Tasks with webgl
regular Tasks will work on webgl
as long as you're not touching the threadPool
even if you had to do Task.Run, you can simply await it await Task.Run(async ()=> {})
Hello friends. Could you tell me why, when I run this code: https://hastebin.com/share/umogihotub.csharp, Unity tells me after apoapsisOffsetY calculation: "Sine: 8.742278E-08." I feel like I'm going bonkers. Isn't sine of -180 degrees = 0?
ohhhhh, I looked at it once more
Double-checked with calculators and Google, but Unity disagrees.
For some reason, it calculates sin(-180°) as 0.8011526.
8.742278E-08 is scientific notation for about 0.000000087 which is within floating point error range
True, I could round the value. But the initial sine calculation goes wrong somewhere, and I don't get why it gives me 0.8011526 when it ought to be zero.
you can never expect a float variable to have an exact value, that is just the nature of floating point maths
Log the values of the variables, not just the end result
Is it because I'm trying to do a sine of a negative number? sin(180°) is properly 0 (Unity confirms it), so I guess I could just switch the sign after the calculation is done.
Thanks, guys, I'll give that a shot.
Where do you get the 0.8011526 result?
From doing Mathf.Sin(angle - 180.0f) before converting to radians. (angle is 0.0f)
Wait, is it my maths that's bad?..
You can't convert it to radians afterwards. 180 rad is 10313 degrees
You're right. Sorry, it's my tired brain. I'll redo the formula tomorrow.
Why can't I use AddForceExplosion? Is it because I'm using RigidBody2D?
Does rigidbody2d have that method? Did you check the documentation?
What does this mean? It's happening when I'm making a method
post the full !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.
Figured it out
Distance is 0 so you divide the direction vector by 0
Is there ever a point I will not use tutorials for pretty much all mechanics in my game? It seems like I can have an idea say "pickup and highlight and object, and place it in a grid system. Seems easy enough to code, but the minute i start to think about chicken or the egg i look up a tutorial lol
Yes, the more experienced you become and the more you repeatedly do things, the less you look up. However, you'll never stop looking up things.. even the most experienced devs still lookup basic things
half the work is learning the tools. You may know a bunch of lighting algorithms and the general idea of rendering meshes, but it's not exactly the same as rendering it directly through opengl
okay, i see the progress, where i was looking up the usual "How to make a game in unity" to now more specific things you cant really find a good video or documentation on, so i know im doin somethin right. I just dont wanna get stuck bc i dont know what to look for or learn next
I want to instantiate an object at a particles position. Does anyone know how I could do that? This is my code at the moment
instantiate has like 10 different overloads
I know how to instantiate at a specific position, I just can't figure out how to get the position of the particles from my particle system
that's a little trickier
read the particle system docs
usually you just use the system's pivot for* the destination
don't need to read the particle system docs, for some reason I was thinking of instantiating something where the particles collide. If all you want is to just instantiate where the particles start... then yeah, just the system pivot. ExplosionParticles.transform.position
hey so at a certain point in my game i need the player to bedisabled basically so the best way i found to do this is disable his sprite render and input system but i want him to still be able to pause the game and stuff how would i just stop him from using certain keys or smth
im using c# events for the input system btw
Well, I have a particle system parented to another particle system as a sub emitter. I want to instantiate an object at the child particle system, but when I try, it instantiates it at the parent particle system
yes. because you're not giving it the correct position.. just get the position of the transform you want to spawn it at
The position I want to spawn it at is the position of the particle after it has been emitted, but it's different each time it's emitted
So I need to get the position of the particle each time it's emitted, I'm just not sure how
☝️
and google -> unity get collision point of particle
particle system has collisional triggers which is useful for cascading systems
I dont want it to instantiate when the particles collide. I want to instantiate it when the parent particle ends or the child particle starts
Hey guys, I'm in need of some help, what does this mean? :,)
Probably you wanna use GetComponentS not GetComponent.
foreach need enumerable
GetComponentInChildren returns exactly one (or zero) component so it doesn't make sense to foreach over it
Oh yeah that worked!! Thanks a lot :)
foreach is interesting -- it doesn't check if the thing is IEnumerable or IEnumerable<T>
It just..directly looks for a GetEnumerator method
I presume this is for compatibility with some ridiculous Windows thing from 1932
Can you check if a coroutine is running and stop it early or interrupt the yield new wait for seconds for example?
You can cache the coroutine, check if it's null or not (running), and call StopCoroutine on it
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
No, this is basically .NET and its weird hardcoded system
Same with await, where it checks for GetAwaiter to check if something is awaitable
It's their way of implementing these keywords
There are plenty like these, one of the newer ones being Deconstruct, which allows you to deconstruct a type implicitly.
Guess it makes sense since you don't want to specify interfaces for these things, but still weird to have a vague feature like this
foreach is a wonderful feature
i make many of my custom data structures implement IEnumerable<> to naturally use it
and some of them have methods that return different Ienumerable<> for different ways to enumerate
I use it in quite a few places, yeah
Here's Deconstruct using the same implicit syntax, for example: https://giannisakritidis.com/blog/Deconstructing-method/
https://github.com/LoupAndSnoop/GenericDataStructures/blob/main/ForestGraph.cs
This one has a ton of Ienumerables. I probably shared this before
it’s a data structure that represents a hierarchy
with several IEnumerables to query said hierarchy
Hey, so I'm having a problem with my character movement, when I go from left to right, it seems my flip script is wrong and it seems to be moving my character too far, so it looks really unnatural. Here is two screen shots (one click of left and one click of right)
and here is my script.
anybody know why this might be happening?
The difference between this one and others is that it tries to maintain hierarchy when deleting or moving things around. Like if you delete a node in hierarchy, its children all go to root, and all their children keep their same connectivity.
!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.
use a pastebin. no one wants to download .cs files. that’s sketchy
well, moreso it's just annoying for mobile users
It shows correctly for me
and then i have to expand the giant embed and scroll up and down
I guess mobile users will need to download
you can view it in discord, you dont need to download anything
please follow the instructions
just "expand"
no
using a paste site works for all users and prevents me from having to scroll up and down in discord
just follow the community guidelines
it also provides line numbers
if you are asking for help, you need to follow the rules of the place where you are asking for help
Do you have a video of the behavior by any chance?
yes, good
flip should not do “if facing wrong direction, then flip.” It should just assign correct direction
How big are the bounds of your image and in general?
erm
I guess you actually need to flip the sprite rather than the whole gameobject
don’t. do flip the scale
flipping the sprite always leads to issues, because transform.right etc is no longer correctly aligned
transform.right can now refer to behind or front of player
so instead of localScale what would i use? is that what you mean
but I think editting local scale like this might be the issue
I think your sprite is off by a certain offset, it does not look centered
Perhaps validate it's actually centered in play mode?
Select the object whose local scale you're flipping and look at where the handles appear in the scene view.
ahhh you're right, my "player" game object was miles away
(and make sure the scene view is on "Pivot", not "Center", when doing this)
oh right, where is the origin
is the origin of your transform in the middle of the collider/sprite?
Your sprite seems to adjust itself in play mode. Are you moving it around?
if the origin is to the right of the player, you are flipping around that point
that fixed it thanks, is there a better way to program this though, so it doesn't happen? or is it just that i was being a doofus 😄
Might just be the camera changing tho
what is the offset of your collider and sprite?
yeah the origin was quite far to the right/up
You can always script it to the center 😛
But always make sure it's centered yourself
that’s your problem
your program can’t really understand that easily. you should set that via unity inspector
i should add, ive been programming for a whole two days 😛
Rest is important or you will make horrible mistakes
still better than a lot I’ve seen tbh
btw, it would help to start making a habbit of making docstrings
yeah i started a fresh project today because i had a power cut and lost an entire days progress 😦
docstrings?
right before a method/field/property, write ///
would you mind showing me an example?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/documentation-comments See the example
visualstudio will autocomplete to
///<summary>
///
///</summary>
/// <summary>
/// Class <c>Point</c> models a point in a two-dimensional plane.
/// </summary>
public class Point
{
/// <summary>
/// Method <c>Draw</c> renders the point.
/// </summary>
void Draw() {...}
}
then you write information there
i thought you did // for comments or is this completely different lol
///<summary>
/// Query colliders in the scene to update the player’s grounding state variables.
///</summary>
private void UpdateGroundingState() {
….
This is kind of the same
But these actually show up in your editor when you hover over a class/method
ngl i just shove my code into an AI and say "comment please"
The idea is that it explains the class/method/property
this is different. with exactly this format, now whenever you use that function, mousing over it in visual studio opens a tooltip that shows that docstring
There are a lot of them. Most common one is summary but you can also add parameter documentation and such. Just type /// above a property, class or method and it will autocomplete everything you could specify
ohhh thats cool
AI comments are literal garbage
Then try making an instance of a class and hover over whatever you commented.
so /// is viewable outside of the visual studio window?
No, inside
you’ll get shit like
// Loop over i
for (int i = 0; i < 5; i++){
The idea is that you, for example, make a class with this. When you then add a new instance of the class you can hover over the type and get explanation of what it is
// makes a comment. Anything you write after is also commented.
/// with those extra xml tags lets visual studio generate all the info to make proper documentation automatically
not just “this is a comment”, but “this is a comment that I actually want to tie to the function so I can read it without openning the file”
ah so i will need to learn the xml tags
Pretty much
VS will autocomplete all that shit for you
Notice it now shows this summary if I hover over the class type for example
That's the idea
i use it all the time, and the only xml tag I really use is <summary> and </summary>
how do make a gameobject follow the mouse cursor?
Honestly mostly useful when you release code publicly because other users won't know your code so I have no idea why this is suggested. Your code should mostly document itself and if you forgot how it works then usually the naming of methods and classes should explain the usage
make a script, read mouse position, convert from screen space to world space, send gameobject there
Remember writing comments means the class/property/method does or represents this exact thing. Often you might apply changes that could actually change the behavior and this means needing to keep your comments up to date. That's why often it's suggested you keep writing comments to a minimum
not true. I use it all the time because once you have a lot of files, it becomes tedious to keep up with them, and keep openning up files to read documentation
See previous message, it's a chore to update
your code should be mostly self documenting, so docstrings should not do heavy lifting at any rate. But you do want to tie docstrings
oh sweet thank you so much
Only applies to code that won't change. Somebody developing their game is guaranteed to change everything
that is a lot of information to take in, could you recommend a video i can watch?
So yeah keep that in mind when writing all the comments
Not really. Just try them out and see if you like it I guess 🤷♂️
so what are they called?
i don’t update my docstrings unless I radically change the purpose of a method. Docstrings should say what a function SHOULD do. Not HOW it does it
Docstrings
okay thanks
Just keep in mind that if you start changing your code the comment should still represent the feature, or it will be very confusing for you and others
and if you change what a function SHOULD do a lot, then something is wrong
how long have you guys been programming? you sound very versed 😄
Yeah that's not something I expect learning beginners to maintain
on and off for maybe 15 years or so
damn son!
I started writing ACS in september 2013 so I suppose 11 years by now
wow
Which was horrible code but I guess you start somewhere
i wish i stuck with it. ive picked it up a few times, then burnt out
but im in it for the stay now, learning with a friend so we can share the motivation 😄
proper documentation is key. the most likely person to use your code is yourself months in the future when you don’t remember jack shit about what you were doing
But let's not strive off too much because that's not the point of the channel 😎
seeing a weird thing and not knowing why you did the weird thing can be paralyzing
how would i move an object using physics (rigidbody 2d) without using "Horizontal"/"Vertical" input? (i want to use buttons for moving the character)
i’m still traumatized by code I inheritted in grad school
i think at this point, id have a better job just linking the video that told me to write the code in the comments 😂
i did figure out how to get a wand to pivot on a hand though and have it shoot spells from a shotPoint which i was quite proud of. Lost yesterday in the power cut though ._.
I probably shared this story before.
It was code to operate a custom-controlled AFM (atomic force microscope). The computer reads raw-ass voltage vs time, and this needs a lot of math to convert from volts to distance to force to corrected force, put into an actual model, etc.
The code I inheritted used a ton of high level math from a high level physics paper to interpret results. The grad student who worked on it graduated, and I inheritted the biggest flaming pile of dogshit code i’ve ever seen.
haha i can imagine, did he not comment at all?
The whole script was one function ~2000 lines long. No local functions. No comments. He used 20 variables, all with one letter names. Literally a-n, s-z etc.
oh wow
In that one function, there were several integrals, regressions, unit conversions, callibrations, formulas from papers.
literally indecipherable
i guess he must have wrote it all in one go and then never needed to go back to it? or maybe he used notes on paper
point being, don’t be that guy
Do you try and use cinemachine on your character controls? Does it make things easier than using normal camera?
we had to abandon it entirely, because there was no one in the world capable of actually using that code
idk how the hell he did it, and it also makes me question if he did it right
and there is effectively no way to check
The first time you write something it's very obvious what happends
But after merely two weeks it becomes a puzzle, even if you maintained it
I think the biggest point to make here is make readable code and use principles that have been established for years
How do i make it only take Position insted?
Realisticly you would never write a massive file or do things like writing very basic variable names or massive amounts of code in general
Instead you'd apply these rules and practices and this would fix the issue, as long as you take time in being consistent
Even comments would not fix this because code has behavior you need to understand by itself
So im trying to do something and im not sure how.
Basically i have a script called "player stats" and in there is health and mana, i want to add each individual thing you can do as a seperate script like spells (because it will have multiple characters) how do i call upon the mana from that stat script and use the value in my flying script?
you don't, that doesn't make any sense. What do you mean by this?
If you only want to pass in the position, then you don't want to change the parent but rather change the position. Just do
collision.gameObject.transform.position = ...
so you cant use a value from one script in another script?
does anyone know how to make script that can make enemy to chase me around ?
You need a reference to the instance of the other script
then you can read values from that instance
okay and how would i do that? 😄
All of the ways in that article are ways to get references
Once you have a reference (from any of those ways), you can access members of that instance of that script.
The big concept you need to understand is that it's not the script you are referencing. The script defines a template for a Component that goes on a GameObject. What you are referencing is a particular Component that was created from that script.
There can be many of copies of it in the scene at a time
that's why you need a reference to a particular one.
okay so im going to have to do a lot of reading on references lol
I guarantee you're overthinking it.
Imagine you're in a neighborhood full of houses.
A reference is a piece of paper that has the address of one of those houses written on it
is it a bad idea to make each component seperate? i thought it would be easier if i had a script for movement, script for stats, script for each spell, then i can just drag and drop them on each player
It is a good idea to separate your concerns into different scripts
It's not necessarily a good idea for each thing to be a component
in the GameObjects/Components sense
but maybe it is for your game
there are no hard and fast universal rules
i think im using it wrong, for me i mean a component being one thing out of many that makes a whole
yes that's what a component is
you can thinki of it as modularly being able to add/remove specific behavior on an object too
yeah thats what i want, because i get confused when there is a billion lines of code doing a billion tasks xD
Handling references is very scary for newbies
but once you get the hang of it it's quite simple
yeah it seems kinda hard
i suppose when i learn the script to write it will be easier, but i have no context for the exmples
like in GetComponent what is it getting? do i write the script name? do I write the player object that the script is assigned to? like its not very clear
GetComponent is a method provided by GameObject and Component.
It looks for a component of the specified type on the game object you're targeting
gameObject.GetComponent<Foo>();
This tries to retrieve a component of type Foo
public class Foo : MonoBehaviour { }
so if i write Mana will it know what i mean?
here if I build for android after project is done. will it still work like I intend it?
it will know what you mean if a type named Mana exists
If Mana is the name of a component, then yes.
If there is no such type, then you get a compile error
i.e. if you have a script defining public class Mana : MonoBehavior somewhere
and the component is like... "public float mana" or no?
A component is a kind of class.
a Component is a whole MonoBehaviour script
You can create your own components by deriving from MonoBehaviour
There are also lots of built-in components, like Transform and MeshRenderer
Object names are irrelevant, as are the names of fields, methods, etc. you declare in your classes
In this screenshot the following things are components:
- Transform
- Mesh Filter
- Mesh Renderer
- Controller
@oak ginkgo
the big sections in the inspector
You make your own when you make scripts and attach them to GameObjects
for example if float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX; will it still work as swipe on ios??
so the script itself is a component?
you should not multiply deltaTime into your mouse input
A script is just a file on your computer that has some C# code in it.
That's it.
No the script defines a type of component.
The component is what you get when you attach it to a GameObject
the script is like a blueprint
If your script defines a class that derives from MonoBehaviour, then the script defines a new kind of component.
thanks. do u have any idea on the android question?
but public class PlayerStats : MonoBehaviour is not a component?
sorry guys its hard lmao
PlayerStats is a kind of component.
thanks for your patience
Since it's a kind of component, you can attach instances of PlayerStats to objects in your scenes and prefabs (through the Add Component button).
thankss
okay so if thats a component, how do i grab a value from inside the component? i only need the one value
You need a reference to an instance of the component.
A specific PlayerStats in your scene.
Think of the difference between a blueprint and a house.
The script is the blueprint
When you drag it onto a GameObject it creates a house from that blueprint. (this is a component)
Hey guys, been stuck on this for too long... Doing my first unity project for a uni assignment and I can't figure out why my ball is constantly spinning in the z axis when it makes a collision, not sure if im missing something?
It has a regular sphere collider, default rigidbody, and a character controller. I have a camera following it with cinemachine but isn't related as bug still persists when disabled fully
This is the script for movement + the small part I have added for collisions which will be used for jumping, im completely lost?
could u explain why? tbh I just memorized that with anything that moves delta time should be used
this rule is wrong.
Deltas are already scaled
it's a close approximation
but it's incorrect
use deltaTime when you need to convert a rate of change to an absolute amount
so this @wintry quarry [SerializeField] private PlayerStats mana;
anything that moves delta time should be used
Unfortunately real life is never as simple as these rigid rules.
Mouse input is already "amount the mouse moved since last frame". This needs to adjustment at all.
Note that with more frames, each frame will capture less mouse movement.
transform.position += velocity * Time.deltaTime;
I need a distance and I have a velocity.
transform.position += mouseDelta * Time.deltaTime;
I need a distance and I had a distance.
Now I have...god knows what
It should not be named mana that makes no sense
it should be named stats or something
And yes that's a way to create a serialzied reference. Now you have to assign the reference in the inspector. Then you can do stats.mana later on
mana is a field in the PlayerStats script
you wouldn't call a reference to the PlayerStats script mana, even though that's what you intend to retrieve from it
i should clarify that:
- it doesn't matter if you have a game object named Mana
- it doesn't matter if the component you want has a field named Mana
- it doesn't matter if you have a field named Mana
- it doesn't matter if you have a variable named Mana
the C# compiler doesn't care about any of this
and neither does Unity when it's executing GetComponent
names are largely irrelevant
I alr watched the junior unity programming course. do u recommend I start watching yt vids of people making games and copy them to learn?
this is frazzling my brain 😛
start using it
it will click eventually
that's beacuse you've made assumptions that are incorrect!
they're incompatible with how unity actually works
a useful rule of thumb: neither C# or unity are magical. there are very well-defined rules about how things work
GetComponent gets a component. It can't do anything other than get a component.
and a component is a very well-defined concept
The "Create Gameplay" section of the documentation provides an overview of important Unity concepts
yeah i get the get component part, i need to call the thing that im trying to take a value for. but how do i then tell unity i want my mana value and not all the other crap
.variable
Share the PlayerStats script with us.
!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.
You access the specific thing you want that's all
myReference.theThingIWant
so in this case like stats.mana
just like transform.position
okay, so PlayerStats is a class
in that class, you have declared a bunch of members -- a member is anything that's part of a class
ok so one problem is currentMana is currently private
public float maxHealth = 100f; declares a field. A field is a variable member.
private void Start() { ... } declares a method. A method is a function member.
If you have a reference to a PlayerStats, you can access any of its members using the . operator.
the member access operator
the name is pretty self-explanatory
PlayerStats stats = GetComponent<PlayerStats>();
stats.maxMana = 12345f;
stats is a variable that holds a PlayerStats. Thus, I am allowed to access any of its public members.
in this case, I set a field's value
public, protected, and private are access modifiers. They control who is allowed to see a member.
can i change "private void Start()" to public?
Why
I don't see a reason to.
public members are visible to everyone; private members are only visible to their own class
So a public field can be read and write by anyone. A private method can only be called by the owning class.
You may be wondering how Unity is running your Start method at all, given that it's private.
Magic
the tl;dr is that it completely skips the normal rules and directly extracts the method from the class
If you want other classes to be able to read currentMana, then currentMana must be a public field.
yeah ive changed them to public
You could also add a method that returns the current mana.
very java-y
The fun middle ground would be to write a property. A property is a member that looks and feels like a field, but actually runs methods.
private float mana = 123;
public float Mana => mana;
Mana simply returns whatever mana contains. There is no way to assign to Mana, so it is read-only.
This can be very useful.
public float ManaPercentage => currentMana / maxMana;
I have a "Vital" class that can report both the absolute value and a percentage
it also lets you set either of them
health.Percentage = 0.6f; // now I have 60 HP out of 100 HP
For now, though, public fields will be perfectly fine.
hi, i want to detect a collision of a gameObject from the script attached to its parent, does that make sense?
If a parent has a Rigidbody on it, then it will receive collision and trigger messages when a child collider produces one
The child will also receive the trigger message (but not a collision message!)
it's an empty object and i just added a circleCollider2D to it
yes
It will receive messages.
what's the difference between
public Transform[] array;
and
public Sprite[] array;
all I see are arrays
that can fit objects into them
They're arrays that store different types
The Transform of the object
The Transform component, which every object in your scene has.
A prefab is an asset that contains a GameObject. You can reference a prefab as any component type on the root of the prefab, or as a GameObject.
Transform can always reference a prefab because every game object has a transform on it
private void Awake()
{
_playerCamera = GetComponentInChildren<Camera>();
_characterController = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
I still see my cursor why is that?
Sprite can reference a prefab if and only if it has a Sprite component on its root.
This is impossible, because Sprite is not a kind of component.
Did you click into the game view?
SpriteRenderer, on the other hand, would work for anything with a SpriteRenderer on its root.
😉
I did yes
Sprite is a kind of asset. You can reference such an asset from a Sprite field.
My first person mouse movement works just fine but I still see my cursor.
ohhh so
public GameObject[] gameObjects; is better??
It's the worst way to reference a prefab, IMO
because it's so vague
it can reference any prefab, regardless of what components it has
If you don't actually care about any properties of the prefabs, then sure, that's the right choice
But if you want prefabs with Projectile components on them, then Projectile[] would be appropriate.
This rule applies for non-prefab references, too.
You should be as specific as possible.
ah okay I understand . so let's say I made a component named Fen; I then type public Fen[] Fenjects;
I only have five serialized references to GameObject in my entire project. All of them are for things I'm just calling SetActive on
Right.
FindObjectsOfType in my script below is obselete - how else do i do this?
PlayerHealth[] players = FindObjectsOfType<PlayerHealth>();
foreach (PlayerHealth player in players)
{
playerScores[player.playerId] = 0;
}
the new method is FindObjectsByType
It was introduced so that you can choose whether or not you want the objects in sorted order
the drawback is that you have to pass a hideously long enum argument to it...
FindObjectsByType<Component>(FindObjectsSortMode.InstanceID)
like this?
PlayerHealth[] players = FindObjectsByType<PlayerHealth>(FindObjectsSortMode.None);
foreach (PlayerHealth player in players)
{
playerScores[player.playerId] = 0;
}
I wish it defaulted to not being sorted.
Right.
ty 🙂
oh god why -- the two-argument version puts the sort mode as the second argument
ok new issue
PlayerHealth[] players = FindObjectsByType<PlayerHealth>(FindObjectsSortMode.None); doesnt find any objects with the script?
that means that no PlayerHealth objects exist at that moment
they certainly do
could it be that the script is search for them before they spawn?
Sure. I don't know which order you're doing things in.
If you spawn the players after you run that code, it will not find any players.
GameManger is searching for PlayerHealth scripts on Startup
If you're spawning players in one object's Start method and searching for them in another object's Start method, and both methods run in the same frame, the order is uncertain
it will depend on creation order
i see
I would have the player spawner provide an event
public event System.Action<Player> OnPlayerSpawn;
Other things can subscribe to this event to be notified when a player spawns
Set up your subscriptions first, then start spawning players
ok, i'll look into that
technically though, the players are not spawning via a manager
You can also events to help enforce the order you do things in
not yet at least, that are just placed within the scene
the game controller can have OnGameSetup and OnGameStart
If the players are in the scene from the start, then FindObjectsByType will find them.
as long as it's not running before scene load or something
its probably not the right way about it, but would a Coroutine work?
a coroutine allows you to run a method over multiple frames
this can be handy for delaying by a single frame or something
you should figure out why this isn't working, though
private void Start()
{
StartCoroutine(PlayerCheck());
}
private IEnumerator PlayerCheck()
{
yield return new WaitForSeconds(0.5f);
PlayerHealth[] players = FindObjectsByType<PlayerHealth>(FindObjectsSortMode.None);
foreach (PlayerHealth player in players)
{
playerScores[player.playerId] = 0;
}
}
No delaying should be required at all if the players are placed in the scene before the game starts.
so i added a 2 second delay and a debug.log, the debug.log was successful but still no objects with that script added into my list
do your players actually have a PlayerHealth component on them..?
they do
show me the inspector for the player as well as the PlayerHealth script
note that the "Players" list/array isn't going to get populated with players
you're storing the result of FindObjectsByType into a local variable
oh wait, so does that mean it could be working and i'm looking at the wrong thing?
Yes.
so this script could be working as intended
if you want to store a list of players, then don't just store the result of FindObjectsByType into a local variable
because I'm storing the playerId into a Dictionary with playerScores
essentially i'm trying to keep track of player scores between scenes
4 players pvp, if all players die apart form 1, the last player earns a point which is then recorded to the GameManger in the Dictionary playerScores variable. The scene will then change and the 4 player pvp starts again with the scores updated and retained. Now i'm questionning if this is the right way about it
could someone explain this to me
void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
I know that void awake does stuff just when the program starts and I understand that it get's the sprite's components before the game starts. But I don't get why I should do this and what diff it makes
Not before the game starts. It gets the sprite renderer attached to the same object that script is attached to on the first frame the object is "alive"
You need to get a reference to things in order to use them, and GetComponent is one of the ways you do that
You could have also done a "serialized reference", where you just drag and drop the component via the inspector
so at the first frame. sprite renderer tells the object if it's alive or not and the way spriteRenderer knows is because GetComponent told it so
Awake is a special method. Unity has a set of messages it can send to your MonoBehaviour classes.
Awake gets run immediately after a component is created, as long as the game object it's on is activated.
or not necessarily "alive" any components
You store the result of GetComponent<SpriteRenderer>() into the variable, yes.
damn kinda complicated . reminds of the set and get functions in C++
No. The sprite renderer doesn't do anything. You just look for it and save a reference to it
Edit: oh, laggy. Fen is explaining
I need help on my code. Specifically the for statement in Confirm(). The issue is that it skips even numbers. The Debug shows
"im made 1"
"im made 3"
"im made 5"
https://hatebin.com/hjycafscbs
The Confirm() happens by a button click
I am a begginer when it comes to programing and unity so please be patient with me, the problem I am having is that I want to make floating DMGnumbers in 3D, I honestly think that I setup everything how it should be, but it seems like when instantiating my text there is a problem somewhere, let me explain:
I made an empty game object then attached a canvas to it which holds a textmeshpro as a child
Then made it a prefab(the whole empty object)
This empty object has a script that says where I hit my enemy(place where it instantiates)
and public textmeshpro for the well... textmeshpro in my canvas
OK this has been said, now the problem since this is a prefab I can't drag my textmeshpro into the inspector of the empty object nor the public transform of my camera(ttansform.lookat(playerCam,vector.up))
If smth is not clear I get it, but if there is someone who wants to help me just DM me if possible 🙂 I'll be greatfull also I will be free in 2 hours maby.
i is increased twice per loop
Because you're increasing it by one before printing it
if ++ did nothing to the variable, then the loop wouldn't work in the first place (:
and if for some reason it was read only inside the loop, you'd get an error when trying to increment it
i++ is shorthand for i += 1
i thought it was read only outside the for(). Ig i learn something new
You may be thinking of how foreach behaves.
You aren't allowed to assign to the foreach variable.
i solved the problem. I just made a local variable to store the 'i' int
Show the inspector with the field you are trying to drag it into
Why not just do i.ToString() ?
Am not on my pc now sorry:(
i need to add 1 just to allign with some of the other scripts
Why do all that instead of just removing the second ++
Ah ok. Well no one can really help you thing. Resend your message when you are prepared to be helped.
Also, no need to do dms, keep it here
Are your other scripts only using odd numbers?
i did removed it
text = $"{i + 1}";
Oh OK, will do then, thx for replying
Oh, you said you made a local variable
nope. But i needed it to start from 1 and not 0
They are saying just assign it directly using formatting
Oh, okay, that makes more sense.
I thought you made an entirely separate variable that you were also incrementing in the loop, which would have been way overkill
int tempNum = i + 1; roomHolder.roomNumberText = tempNum.ToString(); Debug.Log("im made " + i);
code now works as intended. I spent a few hours finding the problem till i decided to use Debug.Log
roomHolder.roomNumberText = $"{i+1}"
Still a bit long, you should just do the thing Carwash suggested
no, literally just
roomHolder.roomNumberText = $"{i + 1}"
ohh
I always forget the term for this, string interpolation? Allows you to put variables inside a string. Start with the $ before the quote marks, and then wrap any vars inside {}
Yep, string interpolation
so your log would become Debug.Log($"I made {i}");
ohh. So insted of doing like
int num1 = 0; int num2 = 0; string test = num1.ToString() + num2.ToString();
I can just do it like this?
int num1 = 0; int num2 = 0; string test = $"{num1}{num2}";
but i get what $ do now
The second will print the sum
ye
the first would give you 00 the second wil give you 0 0
Thanks for the lesson
Hey, im making a cooldown so enemy attacks every 0.5 seconds. how can I add the code to the if function?
Or is there no way?
doesnt make sense.. you could set a bool w/ the timer and check if that bool is true like ableToAttack
its better than trying to rely on the timer and the collision to sync up perfectly
Hey guys, hello
I'm trying yo make a volumetric light effect in Unity 2D URP, like a scanner vfx, I have been researching but haven't find anything useful, I tried with volumetric light but doesn't react to a shadow caster
I want to achieve something like this https://x.com/JuhanaMyllys/status/1668236706548441088?s=20
How could I make this?
could someone help? the code is really long though
I'm trying to make a blackjack card game , and I thought everything was okay no errors and such until when I ran the program it starts giving me
NullReferenceException: Object reference not set to an instance of an object
Then something on the line it says is null but you're trying to do something to it anyway
idk first off I made a card that has an array with all the cards in it
I don't know of any immediately simple ways to achieve this. Maybe #archived-lighting might know more? It could also be pure VFX and not lighting at all, which means #✨┃vfx-and-particles could help? I don't think this is something easily solved in code but I also don't know enough to know what category to even ask this in
Look at the line the error is on. Something on that line is null.
Thanks, I will ask there
here's the code for it
{
public Sprite[] faces;
public Sprite cardback;
SpriteRenderer spriteRenderer;
public int cardIndex; //eg faces[cardIndex];
public void ToggleFace(bool showface)
{
if (showface)
{
spriteRenderer.sprite = faces[cardIndex];
}
else
{
spriteRenderer.sprite = cardback;
}
}
void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
}```
and then I made a debug here's the code for it
{
CardModel cardModel;
public GameObject card;
int cardIndex = 0;
private void Awake()
{
cardModel = card.GetComponent<CardModel>();
}
private void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 100, 29), "Hit me!"))
{
cardModel.cardIndex = cardIndex;
cardModel.ToggleFace(true);
cardIndex++;
if (cardIndex == 52)
{
cardIndex = 0;
cardModel.ToggleFace(false);
}
}
}```
What line is the error on
it's here
Then cardModel is null
Which means either OnGUI is running before Awake or card doesn't have a CardModel component on it
Why do you even have the card variable at all? Just make cardModel public and drag it in
let me try one sec
card does have a cardModel component on it
but in the debug script
OnGUI runs multiple times per frame, and I don't know exactly where or when it runs
what do you see when you click the button here?
Show the inspector of the object you're dragging in
the circled dot
it lists every object in the scene that is compatible with that field
what could I be missing for this not to work: public Image shopImage;
can I enable/disable an image
UI
Define "not work"
wdym by "not work"
i can't enable or disable it
red lines
Okay, so you have errors. What are they
and fix them
read the error
Can you share the updated !code for your debug script
📃 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.
says image doesnt have a definition of enabled
Read the FULL message
not just "image"
it says more than that
it says a full namespace for the class etc.
Assets\KingPlacer.cs(35,23): error CS1061: 'Image' does not contain a definition for 'enabled' and no accessible extension method 'enabled' accepting a first argument of type 'Image' could be found (are you missing a using directive or an assembly reference?)
Ok so which "Image" class is this using?
Looks like you probably have your own class named Image
Do you have a script named Image
still the same
{
CardModel cardModel;
public GameObject card;
int cardIndex = 0;
private void Awake()
{
cardModel = card.GetComponent<CardModel>();
}
private void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 100, 29), "Hit me!"))
{
cardModel.cardIndex = cardIndex;
cardModel.ToggleFace(true);
cardIndex++;
if (cardIndex == 52)
{
cardIndex = 0;
cardModel.ToggleFace(false);
}
}
}```
i think someone else has a class named Image (:
no
right click on the word Image and "Go to Declaration/Definition"
Get rid of the card variable and your Awake method entirely. Make cardModel public and drag it in.
annoyingly, I can't get VSCode to show me the full name for something by hovering over it
ey guys im making a game about cubes and i was just wondering if someone could help me with a quickj issue.So basically i have these cubes with rigidbodies and i need them to walk radom points at certain intervals and all my code is here except when its time for the cubes to move they move really fast and everywhere.I tried to move the object through rb.move and vector3.movetowards are there any suggestions on how to fix this?Heres code and a quick video to demonstarte
Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Worker : MonoBehaviour
{
public GameObject TargetObj;
public bool IsWalkRandomly;
public Vector3 MinWalkValues;
public Vector3 MaxWalkValues;
public int WalkSpeed;
public float TimeBtwnSteps;
Vector3 WalkPoint;
Rigidbody rb;
public bool IsGrounded;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
IsGrounded = Physics.Raycast(transform.position, -transform.up, 1.1f);
if (TargetObj == null && IsGrounded)
{
IsWalkRandomly = true;
}
if(IsWalkRandomly)
{
WalkRandomly();
}
}
void WalkRandomly()
{
TimeBtwnSteps -= Time.deltaTime;
if(TimeBtwnSteps <= 0)
{
float RandX = Random.Range(MinWalkValues.x, MaxWalkValues.x);
float RandZ = Random.Range(MinWalkValues.z, MaxWalkValues.z);
WalkPoint = new Vector3(transform.position.x + RandX, transform.position.y, transform.position.z + RandZ);
TimeBtwnSteps = Random.Range(0, 5);
}
if(TimeBtwnSteps > 0)
{
transform.Translate(WalkPoint * WalkSpeed * Time.deltaTime);
}
}
private void FixedUpdate()
{
}
}
i can't find declaration/definition
notably, show a screenshot of the context menu you get when you right-click on Image
Translate takes an amount to move by, but you're passing it a point to move to.
oh is there any other way to move it without making it fly?i tried rb.moveposition and vector3.movetowards
but it still goes flying radomly and i dk why
its only when its moving
i can comform
Your issue is that you're randomly getting a destination. Instead, randomly get a direction and move in that direction
is this what you mean
Literally the first option
oh ok so should i just subtract the postions?
yeah and that took me to some script
and what was that "some script"?
to get the directions?
What script
some script microsoft made or something
does that sound like Unity's Image class?
You could. If you still want to randomly generate a point and move towards it. You could also use something like Random.insideUnitCircle to get a random direction and move in that direction:
https://docs.unity3d.com/ScriptReference/Random-insideUnitCircle.html
The using directive lets you refer to something from a namespace without providing the full name.
This class is in Microsoft.Unity.VisualStudio.Editor
Get rid of the Using directive for this class
It is curious how it's something Unity-related
in your script with the error
k thank you
Therefore, you have a stray using directive for this namespace
ill try the subtraction method first
You probably wanted the UnityEngine.UI namespace.
having trouble dragging it in
{
public CardModel cardModel;
int cardIndex = 0;
private void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 100, 29), "Hit me!"))
{
cardModel.cardIndex = cardIndex;
cardModel.ToggleFace(true);
cardIndex++;
if (cardIndex == 52)
{
cardIndex = 0;
cardModel.ToggleFace(false);
}
}
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}```
If you "have trouble" dragging it in then the thing you're dragging in doesn't have a CardModel script on it
which is what your original problem was
notice how "Card" shows up in that list
dragging it in should work just fine
were you dragging the "Card" object, or were you grabbing something else entirely?
That list is for variables of type GameObject
They didn't change the type to CardModel yet
this is for a CardModel.
But that screenshot was taken before they changed the variable type
How was that field visible, when the code at that point was this?
#💻┃code-beginner message
Something's wrong with the information being provided. The math ain't mathin'
because the code was modified before the screenshot was taken, presumably
it's still the same
you advised Hermit to make cardModel public
what could be wrong with this?
But they specifically said they hadn't changed anything yet, until after the screenshot was taken
the image is a UI element
We told you what was wrong with this
You're using the wrong Image class
did you read any of the messages we sent you #💻┃code-beginner message
right so this shows the problem. You're put using Microsoft.Unity.VisualStudio.Editor; in your script instead of the correct using UnityEngine.UI;
so it's looking at the wrong Image class
oh okay, that was there automatically
but now the error is on line 13
I do not see this. They said they hadn't changed the script before you instructed them to make cardModel public.
And what line is that
what is the image class for a UI in unity?
The error is going to persist until you assign something to that field.
You just responded to my message where I told you.
i did i just didnt understand
then ask
don't just completely ignore us
thanks it worked now
i feel like I ask too many questions
The message I linked was sent after their screenshot, and the message says the code is "still the same". Still the best explanation is that they lied to one of us at some point
so is a class the thing that comes after 'using' in the start of the script?
ah, I see now
A class is something that comes after the word class
oh okay
Assign a CardModel.
and whats the using thing called
Classes can be placed in a namespace, and that is what you import with using
Everything you've shown indicates that this will work. Drag it in.
This allows you to have multiple classes with the same name, otherwise once someone anywhere in the world made a class named Image you'd never be able to use it again
ohh okay
if i wrote using and then another script name that I made, would it let me access it's variables and functions
the using statement says "Okay, pretend all of the classes in this namespace are part of this project and you can use their names freely"
No. using is used with a namespace.
No, using is for namespaces, not individual scripts
A namespace is a way to organize your types.
and namespaces are made by the program
scripts belong to a namespace. Using a namespace lets you use those scripts
UnityEngine.UI.Button
UnityEngine.UI is the namespace. Button is the type.
You can also make them yourself
oh okay
Have you dragged in an object with a CardModel script on it
Screenshot the exact thing you're trying to drag in
wait wtf
You can't drag in other random objects.
Then the thing you are trying to drag in does not have a CardModel on it
_Debug, notably, does not have a CardModel on it
the card
yes cuz card object has it
Show the full inspector of the card
Show the !code for that CardModel script. Right click -> Edit
📃 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.
Also, for completeness, show the inspector of Main Camera
oh lordy
we've got multiple card model classes
you have both cardModel.cs and CardModel.cs, which presumably declare two different classes
yes is that bad?
Yeah, I had a feeling when I saw the inspector had its name lowercase
I've noticed that Unity's inspector will act like you can assign classes whose names match
(save for casing)
cardModel is not CardModel
they're completely unrelated concepts
Well, one of them is the one you're trying to reference in the Debug script, and one of them is the one you've attached to the Card object
and those are not the same thing
Unity capitalizes the names of things in the inspector, so cardModel and CardModel both appear as "Card Model"
Naming things so similarly that YOU get them confused is bad, yes
so I make all the lower ones big ones?
Why do you have two of them?
Yes, Generally class names should be capitalized, according to most c# style guides
Answer them. Why do you have two
alright
wait
in the debug
I intended
Cardmodel cardmodel
to be a private field
You have not answered the question.
the First one in the script was the one
Please answer the question.
I intended to call
Why do you have two completely different classes that are both named "Card Model"?
Do you even know what these classes do?
u mean scripts?
And also finish a thought before hitting enter.
You have two script files that declare two different classes.
Classes, which are contained in script files
I mean what I write.
I was double checking sorry I'm back. I didn't mean to make 2 different classes. and honestly didn't know how I did
If you did it by accident, you probably renamed a file and then re-saved it in your code editor
Get rid of the duplicate and then fix up any names that are now invalid.
like where in the code do I have 2 classes
@polar acorn i tried doing it withe subtraction but it dident work bc now all the cubes go in the same direction and move in the same direction every play
What did you think fen and digi were talking about when they kept telling you that you have two?
well, a class is declared with the class keyword
so, presumably, both cardModel.cs and CardModel.cs both define a class
classes with very similar names
I thought there's a built in class in unity called CardModel
Ah, no there is not
void WalkRandomly()
{
TimeBtwnSteps -= Time.deltaTime;
if(TimeBtwnSteps <= 0)
{
float RandX = Random.Range(MinWalkValues.x, MaxWalkValues.x);
float RandZ = Random.Range(MinWalkValues.z, MaxWalkValues.z);
WalkPoint = new Vector3(transform.position.x + RandX, transform.position.y, transform.position.z + RandZ);
TimeBtwnSteps = Random.Range(0, 5);
}
if(TimeBtwnSteps > 0)
{
float XDir = WalkPoint.x - transform.position.x;
float YDir = WalkPoint.y - transform.position.y;
Vector3 WalkDir = new Vector3(XDir, 0, YDir);
transform.Translate(WalkDir * WalkSpeed * Time.deltaTime);
}
}```
Disable the parent
It will disable the children
This is what we saw
Hmm, not sure then. Sorry
np
deactivating a game object also renders all children inactive.
disabling a behaviour just disables that behaviour
Ahhhh, yes. That's likely what happened.
I was pretty confused how it didn't get the children
That's what made this so confusing -- the inspector made it look like Card was a valid thing to drag in
I've seen that bug before. I wonder if someone has reported it.
ive been initialising scripts like this, is this necessary
i'm not sure what you mean by "initializing scripts" here -- this is declaring a field
yeah thanks figured it out
That is not initialized. It is declared
im guessing the terminology
but yeah is that how i would declare it
If you want a reference to it. Yes.
I try to have the name different than the type though
public TypeName fieldName;
This declares a field named fieldName that can hold a TypeName
Since it's public, Unity serializies it by default. This means it shows up in the inspector.
Yes edit: no
No, actually.
but i still need to drag it into the box in the inspector right
Script is a meaningless word in this context
bools are false by default isn't it?
Ohhh, I misread. Sorry
Unity did require these names to match until recently.
Yes.
public class MyComponent : MonoBehaviour {
}
This defines a class named MyComponent
It derives from MonoBehaviour.
Ideally, the script file should be named MyComponent.cs
In older versions of Unity, it wouldn't even recognize that you've defined a kind of component if the names weren't correct
what a time!
I am a begginer when it comes to programing and unity so please be patient with me, the problem I am having is that I want to make floating DMGnumbers in 3D, I honestly think that I setup everything how it should be, but it seems like when instantiating my text there is a problem somewhere, let me explain:
I made an empty game object then attached a canvas to it which holds a textmeshpro as a child
Then made it a prefab(the whole empty object)
This empty object has a script that says where I hit my enemy(place where it instantiates)
and public textmeshpro for the well... textmeshpro in my canvas
OK this has been said, now the problem since this is a prefab I can't drag my textmeshpro into the inspector of the empty object nor the public transform of my camera(ttansform.lookat(playerCam,vector.up))
this is what is it showing to me
I understand it but idk how to solve it
I may be stupid but you appear to... destroy the GameObject right after initalizing it.
no that is not happening I can assure that 😄
Also, DMGTaken is never initialized anyway
oh ye it is taken from another script shootingGun
it has the DMG variable as float
hi
Im trying to pre-define dictionary key-values and the value is a struct. How can I access the struct to put a value
you can use new() { } to create an instance of the struct and assign to its fields
new CoolStruct() {
coolness = 1000
}
I want it to move in the direction of the player but idk how??
Thanks!!
or ```cs
CoolStruct coolStruct = new() {
//code
}
the new Struct{ } is easier
My scene has many chair GameObject. How should I manage those chairs and their information?
Should I create ChairManager to find all chair GameObject in the scene and put ChairManager in GameManager (Singleton)? Then my NPC script can access ChairManager to find the closest empty chair.
try using a CharacterController instead
I'll throw in my issue while I'm here.
At work I'm prototyping a game with a simple RigidBody character, and the movement works perfectly fine for our purposes - it'll be replaced soon by an XR controller anyway.
However, there's a weird, small issue I've never noticed before - the mouse look bit in LateUpdate is extremely jittery. I took it from another character controller I made a while back, which itself was from a stackoverflow post (haha), but it's worked flawlessly in every project - until this one. Nobody else at work has a clue what's causing it.
https://hastebin.com/share/onayavoboh.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It's not major, but I am super curious as to what may cause it, as my own research found nothing.
can you recommend a good video to learn c#
you won't be keeping track of naked GameObjects.
you should have a Chair component that stores information about the chair
No one video will teach you everything you need to know about C#, so just go out there and try every beginner tutorial you can find. The most important thing is to keep practicing
If you want just c# then I would reccomend the 4hr tutorial that free code camp has on YT. If you're looking for unity stuff, then blackthornprod had good c# vids
BroCode also has a good series
You mean I should keep track of the chair component and agree with the ChairManager class?
Yes, a ChairManager sounds reasonable.
Each Chair can register itself with the ChairManager in its Awake method.
void Awake() {
GameManager.Instance.chairManager.Register(this);
}
and maybe un-register themselves when they're destroyed, if that can happen
I am a begginer when it comes to programing and unity so please be patient with me, the problem I am having is that I want to make floating DMGnumbers in 3D, I honestly think that I setup everything how it should be, but it seems like when instantiating my text there is a problem somewhere, let me explain:
I made an empty game object then attached a canvas to it which holds a textmeshpro as a child
Then made it a prefab(the whole empty object)
This empty object has a script that says where I hit my enemy(place where it instantiates)
and public textmeshpro for the well... textmeshpro in my canvas
OK this has been said, now the problem since this is a prefab I can't drag my textmeshpro into the inspector of the empty object nor the public transform of my camera(ttansform.lookat(playerCam,vector.up))
the main problem is I cant assign a public Transform and the text mesh PRO to this inspector cuz its a prefab
Sure, I'm just worried I'll create too many manager
And is there a better way to redifine a parameter for a child class? LIke I want a parent to have a bool in false, but its child to false, can I do at parameter declration instead of awake?
This is a pretty common problem.
There is nothing assigned to point text in the inspector
The gist is that whoever spawns the prefab should provide the reference.
You need to assign pointText after spawning the prefab. Whatever spawns this object should have a reference to the text you want to use and set pointText of the object it just made
A child can't "override" a parent field or reinitialize a parent field, no
What you can do is use the Reset method.
Unity calls Reset immediately after you attach a component, or when you right click and hit "Reset"
One other thing: I’ve heard Cinemachine is a good solution for camera-related issues, but I’ve yet to use it.
Here is an example of how I use it
I see... so what should I do? should I just find my main camera inside of my script and assign it to the Transform and then somewhat find the children of this object called pointText and assign it to the... poit TExt right?
public abstract class NamedIdentifiable : Identifiable, IDescribable
{
public LocalizedString Label => label;
public LocalizedString Description => description;
[SerializeField] protected LocalizedString label;
[SerializeField] protected LocalizedString description;
protected virtual void Reset() { }
}
public class GenericChoice : NamedIdentifiable
{
protected override void Reset()
{
base.Reset();
label = new("Generic Config Choice Names", "");
description = new("Generic Config Choice Descriptions", "");
}
}
LateUpdate runs 50 times per second by default. This is not in sync with your framerate, so rotating the camera is going to bereally jittery
Enabling interpolation on the rigidbody might help.
ah, but you're rotating the camera in Update, aren't you?
doesn’t lateupdate just run once per update?
oops
I parsed that as FixedUpdate
how do I make the reference? I can show it to you there it is
Happens
LateFixedUpdate would be a nice thing tbh
wait, no
you are using Update and FixedUpdate
I mistakenly wrote LateUpdate :p
now I'm confused about how I got confused.
I am going insane, I put it in Update

I thought I put it in LateUpdate, but we changed it to Update to see if that helped (it didn’t)
Why use Find? Just store the result of Instantiate in a variable and call Initialize on that
Do you get jitter only whilst moving?
The rigidbody movement is smooth, but if you turn the camera it appears to ‘step’ instead of turn smoothly
yeah, I've seen this exact thing..a lot
well... thats what I did even previously so I used it again
I’ve seen it before but do not recall how I fixed it
I should really write down what I did to resolve it
but ye I see your point
You can almost always avoid Find in all cases
Is your camera probably a child of your rigidbody instead of following and you counter rotate against the rb rotation?
It is a child of my capsule with the rigidbody component
Oh, that's important
transform.Rotate(new Vector3(0, mouseX * mouseSensitivity, 0));
This is going to be fighting with the rigidbody (especially if it has Interpolate enabled)
Oh interesting! Perhaps the reason I never noticed this is because I haven’t used a rigidbody controller before
I would suggest just directly setting the camera's rotation so that it's pointing in the right direction, and then separately making sure the rigidbody's rotation is correct (by setting rigidbody.rotation)
Right, I’ll give that a try, thank you!
I do this to suppress camera shake caused by a character's head rotating
but even if I dod that I cant still figure out how do I find a gameObject take his position and the assign it to my public Transform in my DMGnumbers script I need to look into that and THX.
IF your spawner has a reference to the text you want to use, you can pass that variable to the object you just spawned
So reset... does reset all config?
this text is a prefab so I cant really reference it cuz itss not in thee scene if thats what you ment(as I said I am new to this sorry)
And only in edit mode, just to be clear bout that
So you have one prefab that needs to reference another prefab? You could store the text in a variable when you spawn that, then pass it to the new prefab
Oh, that's a very important thing -- this wouldn't help if you used AddComponent at runtime. Great point.
soert of I will show you, thats the prefab the script is attached to the DMGnumbers and it needs a reference to the pointText
If the prefab for DMGNumbers already contains the pointText object you want to reference you can just drag that in
thats the thing I cant seem to do that its saying type missmatch
I guess you are using TMPro UGUI text