#💻┃code-beginner

1 messages · Page 278 of 1

warped sorrel
#

but I can't hardcode that. it needs to be injected.

rich adder
#
   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)];
   }```
mossy panther
#

Make x a string
Get type returns a string with the name od the class i think

timber tide
#

pretty sure you can just compare types

warped sorrel
#

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

timber tide
#

hmm, aight. I mean technically a lot of this reflection and type stuff is basically string lookups anyway

warped sorrel
#

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.

mossy panther
#

I think

#

If u want it encapsulated in some class same idea

north kiln
#

Generally, if you're using object outside of serialization you're doing something wrong

mossy panther
sick musk
#

Hey how do you render a mesh with textures without creating a new gameobject?

bright zodiac
#

as in swapping the texture?

rocky canyon
#

ud have to copy the renderers material, swap the texture on the copy, and assign the new copy back to the renderer's material

timber tide
#

Well, instanced is good for drawing a bunch of similar meshes, but there's also DrawMesh and DrawMeshNow

sick musk
sick musk
#

Will be checking it out

timber tide
#

Ah, ok right it uses those RenderParams now so DrawMesh and its friends seem obsolete

sick musk
#

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

timber tide
#

because if you took a look at the parameters of DrawMesh it was boarding like 10ish

rich bluff
#

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

rich bluff
#

you had a different name?

sick musk
#

You helped me with a bunch of non-unity code a long time ago. Nevermind it.

desert ocean
#

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

timber tide
#

scope it small, make something out of it, try your shot at it again in your next project

sick musk
#

Not his question

desert ocean
#

this isnt orthodox but i have pretty much one project that i work on

sick musk
#

What about the spell casting system confuses you?

desert ocean
#

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

timber tide
#

oh if it's just a hotbar issue yeah do it like your inventory

#

similar concepts really

sick musk
desert ocean
#

oh and i know of the concepts of coroutines and i heard theyre good

#

what situations should they be used

rocky canyon
#

Whenever u need to use delays or timers

sick musk
sick musk
#

I see no reason why a delay would ever require a coroutine

timber tide
#

sleeping coroutines is somewhat more performative than checking each frame

desert ocean
#

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?

timber tide
#

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

desert ocean
#

gc tax?

timber tide
#

garbage collection since coroutines do create a bit

sick musk
#

garbage collection

desert ocean
#

ah

timber tide
#

pooling coroutines is a thing too, but that's a little more advance

sick musk
desert ocean
#

yea i think that too

rich bluff
#

most people eventually switch away from unity coroutines and use Unitask/MEC or some other implementation

desert ocean
#

my gameidea also includes a bunch of procedural generation but thats a can of worms im not ready to open yet 💀

sick musk
#

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.

desert ocean
#

im already ovewhelming myself lmao

desert ocean
sick musk
#

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.

rocky canyon
#

I use coroutines as a custom ticker for my ai brains 🫠

sick musk
#

So I can't recommend any assets

desert ocean
#

ah

rich bluff
desert ocean
#

im still pretty much a beginner so what you just said is magic to me

rich bluff
#

stick to built in then, they are good for majority of cases

desert ocean
#

will do

sick musk
#

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)

desert ocean
#

snapzones?

sick musk
#

There is also this weird ass desync. I think that's just because I made it render in OnBeforeRender

rich bluff
#

desync maybe because you are sampling the physics controlled position, im not sure whats the fix there

sick musk
#

Desync was due to the onbeforerender thing. I fixed it.

timber tide
#

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.

sick musk
timber tide
#

Unitask is kinda required though if you do want to use Tasks with webgl

bright zodiac
#

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 ()=> {})

cedar nymph
#

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.

keen dew
#

8.742278E-08 is scientific notation for about 0.000000087 which is within floating point error range

cedar nymph
#

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.

languid spire
keen dew
#

Log the values of the variables, not just the end result

cedar nymph
#

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.

keen dew
#

Where do you get the 0.8011526 result?

cedar nymph
#

From doing Mathf.Sin(angle - 180.0f) before converting to radians. (angle is 0.0f)

#

Wait, is it my maths that's bad?..

keen dew
#

You can't convert it to radians afterwards. 180 rad is 10313 degrees

cedar nymph
#

You're right. Sorry, it's my tired brain. I'll redo the formula tomorrow.

west sonnet
#

Why can't I use AddForceExplosion? Is it because I'm using RigidBody2D?

teal viper
west sonnet
#

What does this mean? It's happening when I'm making a method

languid spire
eternal falconBOT
west sonnet
#

Figured it out

timber tide
#

nan bread

#

usually a sign of doing the unthinkable and dividing by zero you monster

keen dew
#

Distance is 0 so you divide the direction vector by 0

vale karma
#

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

hexed terrace
#

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

timber tide
#

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

vale karma
#

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

west sonnet
#

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

timber tide
#

instantiate has like 10 different overloads

west sonnet
#

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

timber tide
#

that's a little trickier

hexed terrace
#

read the particle system docs

timber tide
#

usually you just use the system's pivot for* the destination

hexed terrace
#

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

amber spruce
#

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

west sonnet
#

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

hexed terrace
#

yes. because you're not giving it the correct position.. just get the position of the transform you want to spawn it at

west sonnet
#

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

hexed terrace
#

and google -> unity get collision point of particle

timber tide
#

particle system has collisional triggers which is useful for cascading systems

west sonnet
#

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

hollow scroll
#

Hey guys, I'm in need of some help, what does this mean? :,)

fading coral
#

Probably you wanna use GetComponentS not GetComponent.
foreach need enumerable

keen dew
#

GetComponentInChildren returns exactly one (or zero) component so it doesn't make sense to foreach over it

hollow scroll
swift crag
#

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

stuck palm
#

Can you check if a coroutine is running and stop it early or interrupt the yield new wait for seconds for example?

frosty hound
burnt vapor
#

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

buoyant knot
#

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

swift crag
#

I use it in quite a few places, yeah

burnt vapor
buoyant knot
#

it’s a data structure that represents a hierarchy

#

with several IEnumerables to query said hierarchy

oak ginkgo
#

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?

buoyant knot
#

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.

eternal falconBOT
buoyant knot
#

use a pastebin. no one wants to download .cs files. that’s sketchy

swift crag
#

well, moreso it's just annoying for mobile users

burnt vapor
#

It shows correctly for me

swift crag
#

and then i have to expand the giant embed and scroll up and down

burnt vapor
#

I guess mobile users will need to download

oak ginkgo
#

you can view it in discord, you dont need to download anything

swift crag
oak ginkgo
#

just "expand"

buoyant knot
#

no

swift crag
#

using a paste site works for all users and prevents me from having to scroll up and down in discord

languid spire
swift crag
#

it also provides line numbers

buoyant knot
#

if you are asking for help, you need to follow the rules of the place where you are asking for help

burnt vapor
oak ginkgo
#

did that work?

buoyant knot
#

yes, good

oak ginkgo
buoyant knot
#

flip should not do “if facing wrong direction, then flip.” It should just assign correct direction

burnt vapor
oak ginkgo
#

erm

burnt vapor
#

I guess you actually need to flip the sprite rather than the whole gameobject

buoyant knot
#

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

oak ginkgo
#

so instead of localScale what would i use? is that what you mean

buoyant knot
#

but I think editting local scale like this might be the issue

burnt vapor
#

I think your sprite is off by a certain offset, it does not look centered

#

Perhaps validate it's actually centered in play mode?

swift crag
#

Select the object whose local scale you're flipping and look at where the handles appear in the scene view.

oak ginkgo
#

ahhh you're right, my "player" game object was miles away

burnt vapor
#

It's not in this video atleast

#

Yeah

#

So center it and it will be fixed

swift crag
#

(and make sure the scene view is on "Pivot", not "Center", when doing this)

buoyant knot
#

oh right, where is the origin

#

is the origin of your transform in the middle of the collider/sprite?

burnt vapor
#

Your sprite seems to adjust itself in play mode. Are you moving it around?

buoyant knot
#

if the origin is to the right of the player, you are flipping around that point

oak ginkgo
#

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 😄

burnt vapor
#

Might just be the camera changing tho

buoyant knot
oak ginkgo
#

yeah the origin was quite far to the right/up

burnt vapor
#

But always make sure it's centered yourself

buoyant knot
#

that’s your problem

#

your program can’t really understand that easily. you should set that via unity inspector

oak ginkgo
#

i should add, ive been programming for a whole two days 😛

burnt vapor
#

Rest is important or you will make horrible mistakes

buoyant knot
#

still better than a lot I’ve seen tbh

#

btw, it would help to start making a habbit of making docstrings

oak ginkgo
#

yeah i started a fresh project today because i had a power cut and lost an entire days progress 😦

#

docstrings?

buoyant knot
#

right before a method/field/property, write ///

oak ginkgo
#

would you mind showing me an example?

burnt vapor
buoyant knot
#

visualstudio will autocomplete to
///<summary>
///
///</summary>

burnt vapor
# oak ginkgo would you mind showing me an example?
/// <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() {...}
}
buoyant knot
#

then you write information there

oak ginkgo
#

i thought you did // for comments or is this completely different lol

buoyant knot
#

///<summary>
/// Query colliders in the scene to update the player’s grounding state variables.
///</summary>
private void UpdateGroundingState() {
….

burnt vapor
#

This is kind of the same

#

But these actually show up in your editor when you hover over a class/method

oak ginkgo
#

ngl i just shove my code into an AI and say "comment please"

burnt vapor
#

The idea is that it explains the class/method/property

buoyant knot
#

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

burnt vapor
#

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

oak ginkgo
#

ohhh thats cool

buoyant knot
#

AI comments are literal garbage

burnt vapor
#

Then try making an instance of a class and hover over whatever you commented.

oak ginkgo
#

so /// is viewable outside of the visual studio window?

burnt vapor
#

No, inside

buoyant knot
#

you’ll get shit like
// Loop over i
for (int i = 0; i < 5; i++){

burnt vapor
#

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

buoyant knot
#

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”

oak ginkgo
#

ah so i will need to learn the xml tags

burnt vapor
buoyant knot
#

VS will autocomplete all that shit for you

burnt vapor
#

Notice it now shows this summary if I hover over the class type for example

#

That's the idea

buoyant knot
#

i use it all the time, and the only xml tag I really use is <summary> and </summary>

icy bramble
#

how do make a gameobject follow the mouse cursor?

burnt vapor
#

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

buoyant knot
#

make a script, read mouse position, convert from screen space to world space, send gameobject there

burnt vapor
#

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

buoyant knot
burnt vapor
#

See previous message, it's a chore to update

buoyant knot
#

your code should be mostly self documenting, so docstrings should not do heavy lifting at any rate. But you do want to tie docstrings

burnt vapor
#

Only applies to code that won't change. Somebody developing their game is guaranteed to change everything

oak ginkgo
#

that is a lot of information to take in, could you recommend a video i can watch?

burnt vapor
#

So yeah keep that in mind when writing all the comments

burnt vapor
oak ginkgo
#

so what are they called?

buoyant knot
#

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

burnt vapor
oak ginkgo
#

okay thanks

burnt vapor
#

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

buoyant knot
#

and if you change what a function SHOULD do a lot, then something is wrong

oak ginkgo
#

how long have you guys been programming? you sound very versed 😄

burnt vapor
#

Yeah that's not something I expect learning beginners to maintain

buoyant knot
#

on and off for maybe 15 years or so

oak ginkgo
#

damn son!

burnt vapor
oak ginkgo
#

wow

burnt vapor
#

Which was horrible code but I guess you start somewhere

oak ginkgo
#

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 😄

burnt vapor
#

I still write ACS but the compilers have improved a ton luckily

buoyant knot
#

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

burnt vapor
#

But let's not strive off too much because that's not the point of the channel 😎

swift crag
rancid tinsel
#

how would i move an object using physics (rigidbody 2d) without using "Horizontal"/"Vertical" input? (i want to use buttons for moving the character)

swift crag
#

i usually mention why i made a change in my commit messages

#

but when i don't, ow

buoyant knot
#

i’m still traumatized by code I inheritted in grad school

oak ginkgo
#

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 ._.

buoyant knot
#

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.

oak ginkgo
#

haha i can imagine, did he not comment at all?

buoyant knot
#

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.

oak ginkgo
#

oh wow

buoyant knot
#

In that one function, there were several integrals, regressions, unit conversions, callibrations, formulas from papers.

#

literally indecipherable

oak ginkgo
#

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

buoyant knot
#

point being, don’t be that guy

final kestrel
#

Do you try and use cinemachine on your character controls? Does it make things easier than using normal camera?

buoyant knot
#

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

burnt vapor
#

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

lethal bolt
#

How do i make it only take Position insted?

burnt vapor
#

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

oak ginkgo
#

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?

wintry quarry
modest dust
oak ginkgo
#

so you cant use a value from one script in another script?

queen adder
#

does anyone know how to make script that can make enemy to chase me around ?

wintry quarry
#

then you can read values from that instance

oak ginkgo
#

okay and how would i do that? 😄

oak ginkgo
#

so GetComponent will work in the context i asked?

#

is that the reference you mean?

wintry quarry
#

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.

oak ginkgo
#

okay so im going to have to do a lot of reading on references lol

wintry quarry
#

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

oak ginkgo
#

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

wintry quarry
#

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

oak ginkgo
#

i think im using it wrong, for me i mean a component being one thing out of many that makes a whole

wintry quarry
#

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

oak ginkgo
#

yeah thats what i want, because i get confused when there is a billion lines of code doing a billion tasks xD

wintry quarry
#

Handling references is very scary for newbies

#

but once you get the hang of it it's quite simple

oak ginkgo
#

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

swift crag
#

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 { }
oak ginkgo
#

so if i write Mana will it know what i mean?

maiden yarrow
#

here if I build for android after project is done. will it still work like I intend it?

swift crag
#

it will know what you mean if a type named Mana exists

wintry quarry
swift crag
#

If there is no such type, then you get a compile error

wintry quarry
#

i.e. if you have a script defining public class Mana : MonoBehavior somewhere

oak ginkgo
#

and the component is like... "public float mana" or no?

wintry quarry
#

no

#

that's a field

swift crag
#

A component is a kind of class.

wintry quarry
#

a Component is a whole MonoBehaviour script

swift crag
#

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

wintry quarry
#

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

maiden yarrow
oak ginkgo
#

so the script itself is a component?

wintry quarry
swift crag
#

That's it.

wintry quarry
#

the script is like a blueprint

swift crag
#

If your script defines a class that derives from MonoBehaviour, then the script defines a new kind of component.

maiden yarrow
oak ginkgo
#

but public class PlayerStats : MonoBehaviour is not a component?

#

sorry guys its hard lmao

swift crag
#

PlayerStats is a kind of component.

oak ginkgo
#

thanks for your patience

swift crag
#

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).

oak ginkgo
#

okay so if thats a component, how do i grab a value from inside the component? i only need the one value

swift crag
#

You need a reference to an instance of the component.

#

A specific PlayerStats in your scene.

wintry quarry
oblique sandal
#

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?

https://gyazo.com/cfb96530fc20e1634d0038cbe8709568

maiden yarrow
rocky canyon
#

Deltas are already scaled

swift crag
#

it's a close approximation

#

but it's incorrect

#

use deltaTime when you need to convert a rate of change to an absolute amount

oak ginkgo
#

so this @wintry quarry [SerializeField] private PlayerStats mana;

wintry quarry
swift crag
#
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

wintry quarry
#

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

swift crag
# oak ginkgo so if i write Mana will it know what i mean?

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

maiden yarrow
oak ginkgo
#

this is frazzling my brain 😛

wintry quarry
swift crag
#

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

oak ginkgo
#

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

rocky canyon
#

.variable

swift crag
#

!code

eternal falconBOT
wintry quarry
#

myReference.theThingIWant

#

so in this case like stats.mana

#

just like transform.position

swift crag
#

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

wintry quarry
swift crag
#

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.

oak ginkgo
#

can i change "private void Start()" to public?

rocky canyon
#

Why

swift crag
swift crag
oak ginkgo
#

ohhh i see

#

the float is private above

swift crag
#

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.

rocky canyon
#

Magic

swift crag
#

the tl;dr is that it completely skips the normal rules and directly extracts the method from the class

swift crag
oak ginkgo
#

yeah ive changed them to public

swift crag
#

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.

ornate lynx
#

hi, i want to detect a collision of a gameObject from the script attached to its parent, does that make sense?

swift crag
#

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!)

ornate lynx
#

it's an empty object and i just added a circleCollider2D to it

swift crag
#

where's the parent object, then?

#

does it have a Rigidbody?

ornate lynx
#

yes

swift crag
#

It will receive messages.

ornate lynx
#

this empty object is for checking if it collides with the ground

#

id understand

maiden yarrow
#

what's the difference between
public Transform[] array;
and
public Sprite[] array;

#

all I see are arrays

#

that can fit objects into them

frosty hound
#

They're arrays that store different types

maiden yarrow
#

what's the Trans type?

#

is there one for prefabs?

rocky canyon
#

The Transform of the object

frosty hound
#

The Transform component, which every object in your scene has.

swift crag
#

Transform can always reference a prefab because every game object has a transform on it

final kestrel
#
private void Awake()
    {
        _playerCamera = GetComponentInChildren<Camera>();
        _characterController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

I still see my cursor why is that?

swift crag
#

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.

rocky canyon
swift crag
#

SpriteRenderer, on the other hand, would work for anything with a SpriteRenderer on its root.

#

😉

final kestrel
swift crag
#

Sprite is a kind of asset. You can reference such an asset from a Sprite field.

final kestrel
#

My first person mouse movement works just fine but I still see my cursor.

maiden yarrow
swift crag
#

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.

swift crag
#

You should be as specific as possible.

maiden yarrow
#

ah okay I understand . so let's say I made a component named Fen; I then type public Fen[] Fenjects;

swift crag
#

I only have five serialized references to GameObject in my entire project. All of them are for things I'm just calling SetActive on

tropic marten
#

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;
        }
swift crag
#

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)

tropic marten
#

like this?

        PlayerHealth[] players = FindObjectsByType<PlayerHealth>(FindObjectsSortMode.None);
        foreach (PlayerHealth player in players)
        {
            playerScores[player.playerId] = 0;
        }
swift crag
#

I wish it defaulted to not being sorted.

tropic marten
#

ty 🙂

swift crag
#

oh god why -- the two-argument version puts the sort mode as the second argument

tropic marten
#

ok new issue

#

PlayerHealth[] players = FindObjectsByType<PlayerHealth>(FindObjectsSortMode.None); doesnt find any objects with the script?

swift crag
#

that means that no PlayerHealth objects exist at that moment

tropic marten
#

they certainly do

#

could it be that the script is search for them before they spawn?

swift crag
#

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.

tropic marten
#

GameManger is searching for PlayerHealth scripts on Startup

swift crag
#

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

tropic marten
#

i see

swift crag
#

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

tropic marten
#

ok, i'll look into that

#

technically though, the players are not spawning via a manager

swift crag
#

You can also events to help enforce the order you do things in

tropic marten
#

not yet at least, that are just placed within the scene

swift crag
#

the game controller can have OnGameSetup and OnGameStart

swift crag
#

as long as it's not running before scene load or something

tropic marten
#

its probably not the right way about it, but would a Coroutine work?

swift crag
#

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

tropic marten
#
    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;
        }
    }
swift crag
#

No delaying should be required at all if the players are placed in the scene before the game starts.

tropic marten
#

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

swift crag
#

do your players actually have a PlayerHealth component on them..?

tropic marten
#

they do

swift crag
#

show me the inspector for the player as well as the PlayerHealth script

tropic marten
swift crag
#

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

tropic marten
#

oh wait, so does that mean it could be working and i'm looking at the wrong thing?

swift crag
#

Yes.

tropic marten
#

so this script could be working as intended

swift crag
#

if you want to store a list of players, then don't just store the result of FindObjectsByType into a local variable

tropic marten
#

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

maiden yarrow
#

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

summer stump
maiden yarrow
#

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

swift crag
#

Awake gets run immediately after a component is created, as long as the game object it's on is activated.

maiden yarrow
swift crag
maiden yarrow
#

damn kinda complicated . reminds of the set and get functions in C++

summer stump
grand sigil
#

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

blissful spindle
#

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.

hexed terrace
polar acorn
grand sigil
#

ohh

#

i though it was read only. Thanks

swift crag
#

if ++ did nothing to the variable, then the loop wouldn't work in the first place (:

keen dew
#

and if for some reason it was read only inside the loop, you'd get an error when trying to increment it

summer stump
grand sigil
#

i thought it was read only outside the for(). Ig i learn something new

swift crag
#

You may be thinking of how foreach behaves.

#

You aren't allowed to assign to the foreach variable.

grand sigil
#

i solved the problem. I just made a local variable to store the 'i' int

summer stump
summer stump
blissful spindle
grand sigil
polar acorn
summer stump
polar acorn
grand sigil
hexed terrace
#

text = $"{i + 1}";

grand sigil
#

already did this

blissful spindle
summer stump
grand sigil
summer stump
#

They are saying just assign it directly using formatting

polar acorn
#

I thought you made an entirely separate variable that you were also incrementing in the loop, which would have been way overkill

grand sigil
#

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

summer stump
polar acorn
hexed terrace
#

no, literally just

roomHolder.roomNumberText = $"{i + 1}"

grand sigil
#

ohh

hexed terrace
#

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 {}

hexed terrace
#

so your log would become Debug.Log($"I made {i}");

grand sigil
#

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}";

summer stump
#

Yes

#

Well, sorry no

#

The first will concat the variables

grand sigil
#

but i get what $ do now

summer stump
#

The second will print the sum

grand sigil
#

ye

summer stump
#

So those are different

#

Oh, you edited it

grand sigil
#

i edited it.

#

im guessing thats the correct one

hexed terrace
#

the first would give you 00 the second wil give you 0 0

grand sigil
#

Thanks for the lesson

graceful spruce
#

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?

rocky canyon
#

doesnt make sense.. you could set a bool w/ the timer and check if that bool is true like ableToAttack

graceful spruce
#

actually that might work

#

I'll try it you gave me an idea thank you

rocky canyon
#

its better than trying to rely on the timer and the collision to sync up perfectly

brazen cedar
#

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

#

How could I make this?

maiden yarrow
#

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

polar acorn
maiden yarrow
#

idk first off I made a card that has an array with all the cards in it

polar acorn
polar acorn
maiden yarrow
# maiden yarrow idk first off I made a card that has an array with all the cards in it

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);
            }
        }
    }```
polar acorn
#

What line is the error on

maiden yarrow
#

it's here

polar acorn
#

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

maiden yarrow
#

card does have a cardModel component on it

#

but in the debug script

swift crag
#

OnGUI runs multiple times per frame, and I don't know exactly where or when it runs

maiden yarrow
#

when I drag the card object

#

it gives me "none"

swift crag
#

what do you see when you click the button here?

polar acorn
swift crag
#

the circled dot

#

it lists every object in the scene that is compatible with that field

carmine sierra
#

what could I be missing for this not to work: public Image shopImage;

#

can I enable/disable an image

maiden yarrow
carmine sierra
#

UI

carmine sierra
wintry quarry
#

why not

#

what's stopping you

carmine sierra
#

red lines

wintry quarry
#

You mean you have compile errors

#

you need to read those errors

carmine sierra
polar acorn
wintry quarry
#

and fix them

wintry quarry
polar acorn
eternal falconBOT
carmine sierra
wintry quarry
#

not just "image"

#

it says more than that

#

it says a full namespace for the class etc.

carmine sierra
#

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?)

wintry quarry
polar acorn
maiden yarrow
# polar acorn Can you share the updated !code for your debug script

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);
            }
        }
    }```
swift crag
carmine sierra
wintry quarry
polar acorn
swift crag
#

annoyingly, I can't get VSCode to show me the full name for something by hovering over it

proven mirage
#

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()
    {
        
    }
}
carmine sierra
wintry quarry
#

wdym you can't find it

#

show some screenshots of what you're looking at etc

swift crag
#

notably, show a screenshot of the context menu you get when you right-click on Image

polar acorn
proven mirage
#

but it still goes flying radomly and i dk why

#

its only when its moving

#

i can comform

polar acorn
polar acorn
proven mirage
carmine sierra
#

yeah and that took me to some script

swift crag
#

and what was that "some script"?

proven mirage
#

to get the directions?

polar acorn
carmine sierra
#

some script microsoft made or something

swift crag
#

does that sound like Unity's Image class?

carmine sierra
polar acorn
polar acorn
#

You're using the wrong one

swift crag
#

The using directive lets you refer to something from a namespace without providing the full name.

#

This class is in Microsoft.Unity.VisualStudio.Editor

polar acorn
#

Get rid of the Using directive for this class

swift crag
#

It is curious how it's something Unity-related

polar acorn
#

in your script with the error

swift crag
proven mirage
#

ill try the subtraction method first

swift crag
#

You probably wanted the UnityEngine.UI namespace.

maiden yarrow
# polar acorn Get rid of the `card` variable and your Awake method entirely. Make `cardModel` ...

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()
    {

    }
}```
polar acorn
#

which is what your original problem was

swift crag
#

dragging it in should work just fine

#

were you dragging the "Card" object, or were you grabbing something else entirely?

polar acorn
#

They didn't change the type to CardModel yet

swift crag
#

this is for a CardModel.

polar acorn
#

But that screenshot was taken before they changed the variable type

swift crag
#

the "card model" field was never a GameObject. the "card" field was.

polar acorn
proven mirage
#

@polar acorn

#

like this?

swift crag
maiden yarrow
swift crag
#

you advised Hermit to make cardModel public

carmine sierra
#

what could be wrong with this?

polar acorn
carmine sierra
polar acorn
#

You're using the wrong Image class

swift crag
wintry quarry
# carmine sierra

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

carmine sierra
maiden yarrow
swift crag
polar acorn
carmine sierra
#

what is the image class for a UI in unity?

swift crag
wintry quarry
carmine sierra
swift crag
#

don't just completely ignore us

wintry quarry
carmine sierra
#

thanks it worked now

carmine sierra
polar acorn
carmine sierra
#

so is a class the thing that comes after 'using' in the start of the script?

maiden yarrow
polar acorn
carmine sierra
#

oh okay

swift crag
carmine sierra
#

and whats the using thing called

polar acorn
#

Classes can be placed in a namespace, and that is what you import with using

swift crag
#

Everything you've shown indicates that this will work. Drag it in.

polar acorn
#

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

carmine sierra
#

ohh okay

#

if i wrote using and then another script name that I made, would it let me access it's variables and functions

polar acorn
#

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"

swift crag
polar acorn
swift crag
#

A namespace is a way to organize your types.

carmine sierra
#

and namespaces are made by the program

polar acorn
#

scripts belong to a namespace. Using a namespace lets you use those scripts

swift crag
#
UnityEngine.UI.Button

UnityEngine.UI is the namespace. Button is the type.

polar acorn
carmine sierra
#

oh okay

swift crag
#
using UnityEngine.UI;

...

Button foo;
UnityEngine.UI.Button bar;
#

Both of these work.

polar acorn
maiden yarrow
swift crag
maiden yarrow
#

wait wtf

swift crag
#

You can't drag in other random objects.

polar acorn
swift crag
#

_Debug, notably, does not have a CardModel on it

maiden yarrow
maiden yarrow
polar acorn
maiden yarrow
polar acorn
eternal falconBOT
polar acorn
#

Also, for completeness, show the inspector of Main Camera

maiden yarrow
swift crag
#

oh lordy

maiden yarrow
swift crag
#

we've got multiple card model classes

#

you have both cardModel.cs and CardModel.cs, which presumably declare two different classes

polar acorn
swift crag
#

I've noticed that Unity's inspector will act like you can assign classes whose names match

#

(save for casing)

swift crag
#

they're completely unrelated concepts

polar acorn
# maiden yarrow yes is that bad?

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

swift crag
#

Unity capitalizes the names of things in the inspector, so cardModel and CardModel both appear as "Card Model"

summer stump
maiden yarrow
#

so I make all the lower ones big ones?

polar acorn
swift crag
#

you have two "card model" classes

#

you should probably have one

summer stump
maiden yarrow
#

okay So I'm gonna change all "Cardmodel" types to "PaperModel"

#

will it work?

summer stump
maiden yarrow
#

alright

#

wait

#

in the debug

#

I intended

#

Cardmodel cardmodel

#

to be a private field

swift crag
#

You have not answered the question.

maiden yarrow
#

the First one in the script was the one

swift crag
#

Please answer the question.

maiden yarrow
#

I intended to call

swift crag
#

Why do you have two completely different classes that are both named "Card Model"?

#

Do you even know what these classes do?

maiden yarrow
#

u mean scripts?

summer stump
#

And also finish a thought before hitting enter.

swift crag
#

You have two script files that declare two different classes.

summer stump
swift crag
#

I mean what I write.

maiden yarrow
#

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

swift crag
#

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.

maiden yarrow
#

like where in the code do I have 2 classes

proven mirage
#

@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

summer stump
proven mirage
#

also they go through walls

#

heres video and code

swift crag
#

so, presumably, both cardModel.cs and CardModel.cs both define a class

#

classes with very similar names

maiden yarrow
summer stump
proven mirage
#
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);
          
        }
    }```
carmine sierra
#

can i disable a gameobject and it's children

#

in one line

summer stump
#

It will disable the children

carmine sierra
#

doesn't disable the child

#

its UI

summer stump
summer stump
carmine sierra
#

np

swift crag
#

disabling a behaviour just disables that behaviour

summer stump
#

Ahhhh, yes. That's likely what happened.

#

I was pretty confused how it didn't get the children

maiden yarrow
#

thanks a lot

swift crag
#

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.

carmine sierra
#

ive been initialising scripts like this, is this necessary

swift crag
#

i'm not sure what you mean by "initializing scripts" here -- this is declaring a field

carmine sierra
summer stump
carmine sierra
#

but yeah is that how i would declare it

summer stump
swift crag
#
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.

carmine sierra
#

so the typename is the name of the script

#

why isn't it script fieldname

summer stump
swift crag
carmine sierra
#

but i still need to drag it into the box in the inspector right

summer stump
swift crag
#

The name of a script file doesn't matter.

#

The name of the class it defines matters.

frigid sequoia
#

bools are false by default isn't it?

summer stump
#

Ohhh, I misread. Sorry

swift crag
swift crag
#
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

blissful spindle
#

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

misty hedge
#

I may be stupid but you appear to... destroy the GameObject right after initalizing it.

blissful spindle
#

no that is not happening I can assure that 😄

misty hedge
#

Also, DMGTaken is never initialized anyway

blissful spindle
#

oh ye it is taken from another script shootingGun

#

it has the DMG variable as float

fervent abyss
#

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

swift crag
#

you can use new() { } to create an instance of the struct and assign to its fields

#
new CoolStruct() {
  coolness = 1000
}
lethal bolt
#

I want it to move in the direction of the player but idk how??

swift sedge
#

or ```cs
CoolStruct coolStruct = new() {
//code
}

fervent abyss
charred heart
#

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.

swift sedge
misty hedge
#

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

#

It's not major, but I am super curious as to what may cause it, as my own research found nothing.

opaque mortar
#

can you recommend a good video to learn c#

swift crag
#

you should have a Chair component that stores information about the chair

misty hedge
swift elbow
swift sedge
#

BroCode also has a good series

charred heart
swift crag
#

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

blissful spindle
#

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

charred heart
frigid sequoia
#

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?

swift elbow
swift crag
#

The gist is that whoever spawns the prefab should provide the reference.

polar acorn
swift crag
#

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"

misty hedge
swift crag
#

Here is an example of how I use it

blissful spindle
# swift crag This is a pretty common problem.

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?

swift crag
# swift crag Here is an example of how I use it
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", "");
    }
}
swift crag
#

Enabling interpolation on the rigidbody might help.

#

ah, but you're rotating the camera in Update, aren't you?

misty hedge
#

LateUpdate, yeah

#

Interp is on, btw, that’s the first thing I checked

buoyant knot
swift crag
#

I parsed that as FixedUpdate

blissful spindle
misty hedge
#

Happens

buoyant knot
#

LateFixedUpdate would be a nice thing tbh

swift crag
#

wait, no

#

you are using Update and FixedUpdate

#

I mistakenly wrote LateUpdate :p

#

now I'm confused about how I got confused.

misty hedge
#

I am going insane, I put it in Update

swift crag
misty hedge
#

I thought I put it in LateUpdate, but we changed it to Update to see if that helped (it didn’t)

polar acorn
misty hedge
#

SORRY no

#

LateUpdate

#

God I am actually losing it

swift crag
#

Do you get jitter only whilst moving?

misty hedge
#

The rigidbody movement is smooth, but if you turn the camera it appears to ‘step’ instead of turn smoothly

swift crag
#

yeah, I've seen this exact thing..a lot

blissful spindle
misty hedge
#

I’ve seen it before but do not recall how I fixed it

swift crag
#

I should really write down what I did to resolve it

polar acorn
astral falcon
misty hedge
#

It is a child of my capsule with the rigidbody component

swift crag
#

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)

misty hedge
#

Oh interesting! Perhaps the reason I never noticed this is because I haven’t used a rigidbody controller before

swift crag
#

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)

misty hedge
#

Right, I’ll give that a try, thank you!

swift crag
blissful spindle
polar acorn
frigid sequoia
blissful spindle
swift crag
#

notably, it runs right after attaching a component

astral falcon
#

And only in edit mode, just to be clear bout that

polar acorn
swift crag
blissful spindle
polar acorn
blissful spindle
astral falcon
#

I guess you are using TMPro UGUI text