#archived-code-general

1 messages ยท Page 183 of 1

steady moat
#

It is not. You should divide your singleton in multiple part.

#

Ideally having a sort of ServiceLocator pattern. (It can be multiple singleton)

warm aspen
#

It basically stores game data and tells the save game class to save it to file. Why divide it?

steady moat
#

Because, you want to keep different concept at different location to reduce the overall complexity

#

It helps with maintanability and readability

#

A GameManager, should a manager that manage the game. By example the current state of the game. (In Menu vs In Level)

kind nimbus
#

Hey, im new to using unity and im trying to set up my unity project with the mirror asset added but now that ive created a script and tried to load it up too edit using visual studio i cant use the mirror reference and all the mirror references come up as incompatible

#

Am i just missing some extensions for visual studio or something else?

warm aspen
steady moat
#

As your game grow, you will need to separate the different concept. Otherwise you gonna struggle with keeping your code tidy and simple.

warm aspen
drowsy heron
#

help pls

warm aspen
warm aspen
#

Ok, I don't know

mystic ferry
#

okay so let's say I want to make an inventory system by making a grid array of image components. In order to register clicks to put/take items in/out, I would simply implement the IPointerClickHandler interface, and the respective OnPointerClick method. How does the engine know when the mouse position is inside the bounds of one of the image components to call the callback? My assumption would be that pointerEventdata sends the callback function the gameobject's position and the callback does some math to determine whether the mouse position is within the bounds of the gameobject. How accurate is that?

thick terrace
mystic ferry
compact ice
#

Hi guys, is it possible to see which object in scene or prefab call a method ? For example in the picture i can click on "Unity Script (2 assets references)" and it will show me which object have this class.
Is it possible to do the same but with method/function ?

prime depot
# drowsy heron help pls

Screen.GetDisplayLayout is unity's method. If you want to use it somewhere,just type Screen.GetDisplayLayout(yourList);

prime depot
# drowsy heron help pls

It can be something like this:
var displays = new List<DisplayInfo>();
Screen.GetDisplayLayout(displays);

drowsy heron
steady moat
#

That being said, the information is there at some place, so they might have some tool that is able to do that.

#

(As far as I know)

halcyon radish
#

Hey guys, is it normal for OnEnable to run when starting the application even if the script is disabled? I have never encounter this before until today.

leaden ice
#

not sure about VS

leaden ice
#

perhaps you have another instance of the script in the scene that is enabled

halcyon radish
#

I did a check of the GetInstanceID when starting the application. First the instance ID is 9935592, but on the second time it was triggered, it was -3044834. I was wondering because its negative, is there a random instance intialised somewhere.

halcyon radish
leaden ice
#

the negative instance id indicates an instance in a scene created at runtime

#

the positive ID is an instance from an asset (such as a prefab) or in the scene at edit time (I think)

halcyon radish
#

Ahhh, I see. I guess it could be something with my donotdestroy, which I have a version that instantiates from an addressable. I'll explore that. Thanks, that makes sense.

teal jungle
#

guess what i fucking set it

  [Server]
   public void HandleMovement()
   {
       Vector3 moveDirection = Vector3.zero;

       if ((movingTo & 1) != 0) moveDirection.x -= 1; // Left
       if ((movingTo & 2) != 0) moveDirection.x += 1; // Right
       if ((movingTo & 4) != 0) moveDirection.z -= 1; // Down
       if ((movingTo & 8) != 0) moveDirection.z += 1; // Up

       moveDirection.Normalize();

       if (isSprinting)
       {
           moveDirection *= sprintMultiplier;
       }
       if(controller.stepOffset != 0.0f){
           controller.stepOffset = 0.0f;
       }
       if(controller.slopeLimit != 0.0f){
           controller.slopeLimit = 0.0f;
       }
       controller.Move(moveDirection * movementSpeed);

   }
}```
and it still fucking climbs
halcyon radish
#

@leaden ice Thank you for that explanation with the runtime difference with the instance ID. It turns out that even though the addressable trigger that I have for testing and live version for the application. Even though it doesn't actually load, for some reason it affect the DoNotDestroy GameObject. Strange. But atleast now I found the issue. Thanks again.

digital creek
#

Sorry if this is a stupid question where do I find functions in unity document or something like that

west sparrow
# drowsy heron I'm trying to create a system to move the window with the keyboard similar to th...

You can edit the Unity players window bounds as well as make the menu and border transparent, but I've always done that outside of normal unity c#.

https://forum.unity.com/threads/solved-windows-transparent-window-with-opaque-contents-lwa_colorkey.323057/

See above, accessing the user.dll to resize the window.

drowsy heron
digital creek
#

@leaden ice i thought it was a table

west sparrow
leaden ice
leaden ice
heady iris
#

you can switch between the manual and the scripting reference for individual components

#

the manual talks more about what the component is for and how to interact with it in the editor

#

the scripting reference tells you about the class

vapid glen
#

hi guys, quick question. im using a velocity.y on a 2d rigidbody to detect that my player has stopped falling if the result is 0 or lower. and it works fine if i jump to the left. but if i jump to the right when i hit the ground i am stuck with a residual tiny hexadecimal amount of y velocity for as long as i keep walking in that direction, it goes away as soon as i stop touching the joystick. any idea what could be causing this?

robust dome
#

sounds very normal to me since you are using physics here

#

you can manually adjust the velocity or reset it to zero as you wish

prime mica
#

Hey guys, unsure whether this goes here or in beginner. How would I add a sin curve to a transform.up? I'm trying to create a jump function that's independent of rotation, as my character can be in many different orientations, and I am not using physics for my game. Here's the code for jump forwards as it stands. Right now all it does is move the character forwards 2 spaces. ```CS
IEnumerator JumpForwards()
{

    Vector3 oldPosition = movePoint.transform.position;

    float distFromOrigin = Vector3.Distance(transform.position, oldPosition); // get distance from centre point of the cube. old pos is set when space is pressed
                                                                              // so could be different from transform.pos

    Vector3 newPosition = movePoint.transform.position += turnPoint.transform.forward * (jumpDistance - distFromOrigin);

    float t = 0f;

    while (t <= 1)
    {

        if (ball.IsColliding)
        {
            break;
        }

        
        
        movePoint.transform.position = Vector3.Lerp(oldPosition, newPosition, t * moveSpeed);//move forwards 


        if (movePoint.transform.position == newPosition) { break; }

        t += Time.deltaTime;
        yield return new WaitForEndOfFrame();

    }

    StartCoroutine(Fall());
    yield break;
}```
#

I have the forwards movement, I am trying to figure out how to make it go from 0 to a set jump height back down to 0

dense vessel
#

But what height do you want for your jump?

#

I would use f(t) = -h * t * (t - 1) if h is the height of the jump.

#

(And by the way, a jump does not do a sin curve)

prime mica
#

where f = movePoint.transform.forward right?

dense vessel
#

f is the math function to get the height depending on t

#

@prime mica That's f ๐Ÿ™‚
But I'm still not sure if I understood your question, is that what you were looking for?

prime mica
#

yeah that's it

dense vessel
#

What namespace? We can't really help you with that little information ๐Ÿ˜‰

#

And where does it come from?
Did you create it? Is it from an asset?

#

That's weird ๐Ÿค”
So some of the scripts in your project can access it and others can't?

somber nacelle
#

are you using assembly definitions?

dense vessel
#

On the right side of Visual Studio, you only see one assembly right?
(I had the case before where I created one by mistake ๐Ÿ˜… And it was causing the same kind of issues )

somber nacelle
#

because if you were using assembly definitions you would need to make sure that the assembly you are working in has a reference to the assembly that namespace is defined in

prime mica
#

crappy drawing showing what I'm needing. Sorry if it's an obvious answer but I really suck at this part of programming :l

#

when you see the ball slide forwards in the video, that's the "move forwards" part of my jump code

thick terrace
#

my first very lazy thought is to skip all the maths, put an AnimationCurve property on your script, and evaluate the time in the jump to get the height haha

prime mica
#

does that account for the ball's direction? I couldn't have an animation curve moving the y-axis as depending on the orientation, it could move in the wrong direction

#

maybe i'm not understanding it properly haha

dire tinsel
#

Can't remove ParticleSystem because CFX_AutoDestructShuriken (Script) depends on it
Does anyone knows why is this error prompting?

somber nacelle
#

because you have a component on that object that has the RequireComponent attribute requiring a ParticleSystem. so you need to remove the other component first

dire tinsel
#

if (Physics.Raycast(Playercamera.transform.position, Playercamera.transform.forward, out hit))
{
MuzzleFlashVFX.Play();
ParticleSystem impact = Instantiate(shootEffect, hit.point, Quaternion.LookRotation(hit.normal));
//Destroy(impact);

somber nacelle
#

yeah you're destroying the ParticleSystem component instead of the whole gameobject

dire tinsel
#

so what should i do?

#

i should paste that destry code where the object is actually being destroyed?

somber nacelle
#

no, you should destroy impact.gameObject instead of just impact since that is just a reference to the ParticleSystem component on the instantiated object

dire tinsel
#

MuzzleFlashVFX.Play();
ParticleSystem impact = Instantiate(shootEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impact.gameObject);

#

?

#

@somber nacelle

somber nacelle
#

also you probably want a delay on that Destroy, unless you want to destroy the particle system in the same frame you instantiate it

dense vessel
somber nacelle
#

!collab ๐Ÿ‘‡

tawny elkBOT
fierce spear
lucid wigeon
#

Does anybody also have this issue where "Extract method" in VSCode just creates a new method called "NewMethod" instead of allowing me to set a name? That's super weird...

rigid island
#

thats cause VSCode is inferior to VS so I'm not surprised that feature is half broken

lucid wigeon
rigid island
#

if you want to do some proper coding , consider a much better ide like Visual Studio @lucid wigeon

#

intellicode alone makes it worth

lucid wigeon
rigid island
#

!vs

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

hexed pecan
#

Does visual studio automatically give you the rename prompt?

lucid wigeon
lucid wigeon
hexed pecan
#

So in other IDE's it opens the rename field as soon as you extract the method?

lucid wigeon
#

so that you can choose a name for the new method instead of setting it to "NewMethod"

hexed pecan
#

That does make sense, never crossed my mind though

lucid wigeon
hexed pecan
#

Probably depends on the language. That example shows typescript or something

#

I use VSCode and it does not open the rename field automatically with C#.

lucid wigeon
#

I'll have another go at it in some time, but for now VSCode works for me, debugger works, extensions work

rigid island
hexed pecan
#

Yeah but looks like VSCode

hexed pecan
#

It recently got the official extension support back

rigid island
#

I don't hate VSCode ๐Ÿ™‚
I use to replace Notepad++
Unity extension is a step forward but its still half assed and broken. Just sucks that unity did nothing about it but microsoft had to step in and take care of bidness

knotty sun
hexed pecan
#

Worked fine for me 6+ years ๐Ÿ‘

knotty sun
hexed pecan
#

Not sure what your point is

knotty sun
#

my point is you have 6+ years experience using VS Code, you cannot compare that with someone just starting out

hexed pecan
#

You said it doesn't work. I'm saying it has been working without problems for me. That's all, Steve

rigid island
#

to be fair the intellicode / is kinda dogshit on VSCode

knotty sun
#

VS Code as is does not work for Unity development if you are a new beginner. That clear enough for you

hexed pecan
#

Why are you talking about beginners

mystic ferry
#

where's the guy that always butts in saying rider is better than both of them

rigid island
# hexed pecan How so?

just from when i tried it recently,
it doesn't work half the time for unity, doesn't autofill correctly (ie it automatically fills in the wrong things or doubles it)
I'm not trying to be arguementitive ofc we can all use whatever we prefer, just wished they made it better in that aspect

knotty sun
rigid island
hexed pecan
hexed pecan
rigid island
#

you seem the few who's lucky considering the amounts of issues from here , you know this ๐Ÿ˜›

#

for beginners though and unity , its not a good experience to start with

knotty sun
#

Guess what, I have VS, VS Code, Rider and other IDE's, out of preference for functionality I chose VS 90% of the time

hexed pecan
rigid island
#

fair enuf ๐Ÿ˜…

hexed pecan
#

It's been a while since I had to actually set up VSCode from the ground up

swift falcon
#

do somone know how i can change the parent of ui image trough script?

hexed pecan
#

Not sure how big of a hassle it is nowadays

rigid island
#

trust me I have a video on it on my YT , no bullshit ๐Ÿ˜›

#

its a painless process now, but it sometimes decides "fuck that I'm not recognizing the .csproj as valid ones ๐Ÿ™„"

hexed pecan
#

I see

swift falcon
#

thanks

knotty sun
swift falcon
#

ok

swift falcon
#

i will search the next time

knotty sun
swift falcon
#

but it gives me this error UnityEngine.GameObject' to 'UnityEngine.Transform

leaden ice
rigid island
#

says google

leaden ice
#

Transform parents have to be Transforms.

#

pay attention to the types involved

rigid island
# swift falcon

also ur error isn't underlining u might wanna configure ur editor

#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

knotty sun
empty crystal
#

For some reason, the trigger here isn't detecting any collisions with the Blockhead, yet, it's detecting collisions with the player. I made sure both layers are checked in the matrix too. Anyone got any ideas?

cyan bronze
#

Guys. Interested how do people implement building mechanic where you see "Ghost" building before placing. Do people use Proxy pattern to before check every requirements and only then build real object?

rigid island
#

i make it simple and just create a placement version of whatever object with a different material / shader, then use raycasts/boxchecks and such to see if its empty spaces the size of this object

#

Physics.overlaps methods and allthat

rigid island
rigid island
#

find out what ur actually hitting first

empty crystal
#

Wait I see the problem now

#

I feel so stupid

#

Thanks!

#

(It was inside an if statement it wasn't supposed to be inside of)

rigid island
#

ah yeah was gonna say that but Idk ur game lol

#

could be on purpose for all i knew ๐Ÿ˜›

mossy snow
#

are you using assembly definitions?

hexed pecan
#

It does seem like an asmdef thing

leaden ice
#

The HurricaneVR.Framework almost definitely has an assembly definition

#

it won't be able to reference your Assembly-CSharp assembly (aka all your code)

#

by the way why are you modifying the HurricaneVR code? Are you sure that's necessary?

#

I mean exactly that

#

HurricaneVR has an assembly definition in it

#

aka it defines its own assembly that all the code lives in

#

yes those are assemblies

#

and they are defined by the asembly definition files in the asset folder

leaden ice
#

why does that involve modifying the source code?

#

can you not simply interact with their provided API?

#

I mean... calling functions and such in their APi

#

same way you interact with any API

#

same way you interact with the Unity engine

#

you can interact with the unity engine without seeing or modifying the unity engine source code, yes?

#

that does not sound like something that requires modifying source code of Hurricane VR at all

plucky cradle
leaden ice
#

also "shooting" is really something in your own code - hurricane VR is for posing and picking up object in VR right?

#

where are the docs for that

#

yeah but

plucky cradle
leaden ice
#

they're just... obejcts you grab like any other

#

really?

#

You aren't looking very hard

#

there's a whole API documentation section

#

the link you sent

#

i don't really know what this question is asking tbh

#

but 99.999% does not require modfying the source code of the asset in any way

#

so you can simply hook up some function on a custom script of yours to run with from that UnityEvent

#

Look at the inspector for one of the guns- you should see the UnityEvent there (called "Fired")

#

simply add your listener to that

rancid kindle
#

i need help when i try to do Destroy game object it doesnt disappear on my game veiw

hexed pecan
rancid kindle
#

ok

#

and this list contains the correct game objects

rancid kindle
hexed pecan
#

Put some Debug.Logs and find out

rancid kindle
#

ok let me show you

hexed pecan
#

Btw, ToList() is not needed here. Use the array and change .Count to .Length

rancid kindle
#

ok

hexed pecan
#

Are you doing this in edit mode perhaps? Or play mode?

rancid kindle
#

wdym edit mode

hexed pecan
#

When the game is not playing

rancid kindle
#

no

#

the game is playing

#

AND WHEN I CLICK THIS

#

caps

#

and then this bit of code gets run

hexed pecan
#

Well, it should work, not sure what's wrong with your setup.

heady iris
#

if you click it again, do you see an empty list in that method?

rancid kindle
#

yes

#

it menas its deosnt acc get deleted

#

when u delete the parent game object does the children not delete with it?

heady iris
#

If obj is a GameObject, it destroys the GameObject, all its components and all transform children of the GameObject.

#

is anything else trying to spawn new ones?

rancid kindle
#

this is the only other peice of code that will instatiate something

#

but it doesnt get hit right after

#

let me use debug.log to check rq

#

no nothing but i am getting this error

leaden ice
mossy snow
#

that's in his resetMap method, where he news up a NewGame before using Find

rancid kindle
#

ive fixed

#

it

#

the game abject where spawning their own object

#

but that object wasnt gettign destroyed

ornate moon
#

Okay, I can't google a straight answer for this. If I change a scriptable object at runtime in the editor, the changes persist until I restart the editor without saving. If the scriptable object is changed in a build it will only persist as long as the session. So, not wanting to have to build every time I want to test something, how do I stop the editor screwing up my SOs when I test?

leaden ice
heady iris
#

It's actually a bit more nuanced: if you load a new scene in the editor (that doesn't reference the SO), it'll get destroyed and recreated

#

mutating SOs you got from assets is very weird, and I try to avoid it

leaden ice
#

e.g.

void Awake() {
  #if UNITY_EDITOR
  mySo = Instantiate(mySo);
  #endif
}```
heady iris
ornate moon
#

What does Instantiate do here? I googled it and yeah, google is worthless now

heady iris
#

just...consult the unity documentation

ornate moon
#

I DID

ornate moon
#

Two lines

leaden ice
#

it's purple, because I have clicked that link many times

ornate moon
#

That's not the page I got

leaden ice
#

what search term did you use

leaden ice
rugged dragon
#

I'm having a problem with Buttons and partially transparent Sprites. I'm trying to have a clickable door on my UI canvas. I attach a button component and off we go. The problem is that no matter where I click, the button is clicked. This is because the sprite/image for this door is a full screen sprite (I don't want to place the door in the spot, I want the sprite to be full screen with transparency so the door is where it should be). I use the Image.alphaHitTestMinimumThreshold = 0.5f; line and that sort of solves it, but it moves the raycast "hitbox" to the right of the gameobject. Aka, clicking to the right of the door now clicks the button instead of clicking the door. I don't know how to solve this hitbox moving issue.

I know this has been discussed before, but I haven't been able to solve it using the research I found. Even this https://forum.unity.com/threads/image-alphahittestminimumthreshold-not-working-correctly.465586/ which apparently works but not for me.

ornate moon
#

As in, if I set mySo = Another_SO, is mySo Another_SO or a Instantiated copy?

heady iris
#

an assignment doesn't instantiate the SO

#

x = y; just means that x and y reference the same thing

ornate moon
#

right, thought so

#

so every time I change mySo it needs to be instantized

ember cape
#

Hey there, I am unsure if this is the correct channel to ask my question in, if it's not direct me in the right channel and I shall go there.
I am new to Unity and am still learning the platform.
That being said my question is regards to Unity project structuring, now when I say structuring I don't mean the root and/or folder hierarchy, I mean scene-wise.
After doing some research and watching a few videos, I came up with this structure where the _BootLoader contains all my managers/controllers and load/unload my other scenes which can also request and pass data to the _BootLoader
Here is the structure I had in mind, the _BootLoader loads scenes additively.
Is this correct/prescribed/optimal way to structure a multi-scene project?

heady iris
ornate moon
#

ugh yeah. Silly me thought the SO on disk would be read only.

heady iris
#

well, it is.

hexed pecan
heady iris
#

In the editor, the SO gets loaded from the asset when you load the scene

hexed pecan
#

In editor the changes persist

#

In build nope

ornate moon
#

yeeeeeah

heady iris
#

The scene never unloads if you keep it open in the editor

#

When you restart the editor, the asset gets loaded from disk again

shell scarab
heady iris
#

(unless you do something that would make it save the changed, like editing it in the inspector, I guess)

#

I tested this a few months ago because I was really damn confused

rocky helm
#

Are script properties much faster to access and change from other scripts than public variables? Not very familiar with them. In fact, just learned about their existance, but I don't quite understand it yet due to the doc being a little confusing for me.

heady iris
ornate moon
heady iris
#

You need to learn how to write code first

#

Properties are going to be slower, though. A property is just syntactic sugar for a method.

rocky helm
shell scarab
#

what do you mean script properties?

leaden ice
heady iris
shell scarab
#

if it helps @rocky helm, properties are treated as methods.

leaden ice
#

the answer is - they are slower than fields but not slower-enough in general that you need to worry about it unless you are micro optimizing

heady iris
ornate moon
#

Well at least I feel less silly now

rocky helm
shell scarab
#

yea but like, really not by much

knotty sun
shell scarab
ornate moon
simple egret
#

Lua

#

JS

knotty sun
#

yes it does

ember cape
rocky helm
heady iris
knotty sun
#

JS certaily does

knotty sun
#

access modifiers are scope

rocky helm
leaden ice
#

Lua absolutely has scope

rocky helm
leaden ice
#

and public/private is not related to scope

heady iris
#

Access modifiers can influence scope.

knotty sun
leaden ice
#

which actually has scope

heady iris
#

scope is simply the context in which a name is valid

leaden ice
heady iris
#

I'm so used to thinking of scope purely in terms of locals

rocky helm
#

Anyways I don't wish to spark a fire so lets just stop please

leaden ice
ember cape
leaden ice
#

anyway Lua isn't really an object oriented language

#

so the whole idea paradigm of objects doesn't really apply

shell scarab
devout harness
#

Oh I thought that was a typo, you literally mean Luau

leaden ice
ember cape
rocky helm
shell scarab
# ember cape Hey there, I am unsure if this is the correct channel to ask my question in, if ...

in that case, I would not additively load all these scenes. I would have a bootstrap scene that the game loads into that has my DDOLs, load into the main menu scene (or in this case the title scene, which I'm assuming splash displays your game title? If you want that you can put that in the player settings and you don't have to load into a scene first, but it will only appear in a build), then from there load into gameplay scenes

rocky helm
shell scarab
rocky helm
ember cape
shell scarab
ember cape
shell scarab
#

yes

ornate moon
#

Yeah thanks for the help. The last week has been a string of getting nowhere because of weird crap. FUN FACT: most the wrapping options in textmeshpro text boxes do literally nothing! They flat out don't work. That was a fun hour or so figuring that out.

hexed pecan
sharp cloak
#

Since when this doesnt work and how to make it work?

hexed pecan
#

It should show up in the inspector

sharp cloak
#

it doesn't sadly

shell scarab
#

it doesn't show in the inspector?

sharp cloak
knotty sun
hexed pecan
#

Save your file and/or fix compile errors

shell scarab
knotty sun
sharp cloak
#

Where can i find the field to set the array than?

#

oh yea i forgot lol, my bad

shell scarab
sharp cloak
#

i see now

shell scarab
#

if you're looking for default field values, which only work in edit mode, I believe an array will work.

sharp cloak
#

in other scripts it appears

shell scarab
#

yea try an array. But that only works in edit mode, not builds

sharp cloak
#

What would work for build too?

shell scarab
#

use the start or awake method to get the references you need?

leaden ice
#

you need to look at the inspector on an actual instance of the script attached to a GameObject

#

not by clicking on the script asset

knotty sun
shell scarab
#

I'm sorry, I'm not trying to. Please explain how that's nonsensical so I can give better advice.

knotty sun
shell scarab
#

i don't believe you read everything

knotty sun
shell scarab
#

yes, really

shell scarab
sharp cloak
#

What about how to access hierarchy from code?

shell scarab
#

total nonsense?

#

how is that total nonsense?

knotty sun
shell scarab
soft shard
shell scarab
#

if you read what they're asking they want the field to be assignable in the script inspector

sharp cloak
shell scarab
#

I also told them that it only works in edit mode. They asked how to make it work in a build, so I said they need to use the start/awake method to assign objects to the list, which you called nonsensical.

#

which is in of itself, nonsensical

knotty sun
knotty sun
hexed pecan
#

Scripts do allow you to set default values..

shell scarab
hexed pecan
#

It's either reference types or value types only, I forgot which

#

Yea reference types

shell scarab
knotty sun
shell scarab
hexed pecan
#

Yea this part

shell scarab
#

look, I assigned it

soft shard
# sharp cloak i want to find an gameobject by name which isnt anyhow connected to the script

The GameObject class has static functions like .FindObjectOfType and .Find and I believe a few others, though in most cases I would suggest against searching objects by name, simply because its very easy to mistype or rename the object, then your code would no longer work, or if you have 2 objects with the same name, it may only ever return the first one - for that reason its often better to store a reference to the object instead if its already a part of the scene - or if its instantiated instead, you can pass a reference from Instantiate, which returns a Object

shell scarab
#

just because you don't know unity doesn't mean you have to start saying im giving nonsensical advice. There's a more constructive way of questioning the validitiy of what I'm saying.

knotty sun
simple egret
#

Yeah it's like field initializers but from the Inspector

shell scarab
#

yup

sharp cloak
#

[SerializeField] Transform obstaclesBlueprints; What type it has to be for me to be able to assign an object from hierarchy?

shell scarab
#

it just won't work if you try to instantiate an object at runtime

sharp cloak
simple egret
#

Nothing really extraordinary, but useful if you need some default asset

simple egret
sharp cloak
#

Wont let me

#

drag an object there

hexed pecan
jovial valley
soft shard
tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

shell scarab
simple egret
sharp cloak
sharp cloak
#

so i can access its children to form a list in Start void

shell scarab
#

so add the component onto it

#

through the add component menu

sharp cloak
#

sorry?

shell scarab
#

!learn

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

simple egret
#

What are you trying to drag? Where is it located?
Same two questions for the target script of the drag-drop

soft shard
sharp cloak
#

Yeah i mean i am comming back to unity after like 5 years now so i forgot everything and try to finish a project

sharp cloak
shell scarab
#

also i apologize, i think I misunderstood you, you're saying you'd like to drag that gameobject onto that field. Make sure that script is assigned to a gameobject then you wll be able to

shell scarab
jovial valley
#

How come this isnt doing anything? like when the Server rpc is called to legit do nothing but print(), it doesnt even do that??
https://gdl.space/coyufihase.cs

shell scarab
#

if you're trying to drag it into the default reference, only assets can be assigned.

shell scarab
sharp cloak
#

nvm that is a bad idea i see it now

#

lastly, how can i get the children?

shell scarab
sharp cloak
shell scarab
#

you can also use a foreach loop in this way:

foreach(Transform t in transform) {
  Debug.Log(t);
}
soft shard
# sharp cloak it isnt attached anywhere, i am trying to keep this particular script this way

(catching up on chat, but just to explain why its impossible) Scripts that derive from MonoBehaviour can be attached to objects in the scene, those objects can be inspected and have scene objects (or prefabs) referenced to them - if a script does not derive from MonoBehavour, it cannot be attached to a object, and cannot hold direct references, so youd have to pass those references to it through code, and not through the inspector - but prefabs and non-mono scripts cannot keep references to scene objects, since theres no guarantee the scene will ever be loaded, and therefore theres no guarantee the object its referencing will ever exist, or when - Non-mono scripts is a nice approach, one I use often myself, though what was the exact goal/purpose of your non-mono script?

shell scarab
#

so much text now it's getting a bit lost

sharp cloak
soft shard
# shell scarab hi did I miss something? What non mono script?

Maybe I misunderstood something, they mentioned the script wasnt attached to anything and they wanted to keep it that way, which sounds like a non-mono script, as youd usually attach a mono script to some object for references and Unity-specific logic (like Update, Start, etc), if the script IS mono, but they dont plan on using it on a object, it likely could become a non-mono script, depending on the purpose of the script

sharp cloak
#

Why's that?

soft shard
spare otter
#

Hey I recently tried adding a rebinding system into my game everything seems to be working right, but the key isn't rebound how can I fix it?

sharp cloak
shell scarab
shell scarab
# sharp cloak

GetComponentInChildren needs a component type, not a gameobject.

#

if you want to get a gameobject in a child, use one of the other 2 ways I described.

sharp cloak
#

ah damn lol

#

i am trying to get all children in a list

shell scarab
#

you also need GetComponentsInChildren

#

but also, that will literally get every single component assigned to all your children

sharp cloak
#

but not children of children right?

#

i only need those level 1 children

shell scarab
#

my bad, i meant Component.GetComponentsInChildren

shell scarab
sharp cloak
#

and what about only children ?

shell scarab
sharp cloak
#

oh i missed this response, will try it now tho

#

๐Ÿ‘

shell scarab
#

also, obstacles will need to be a list of GameObjects

flint sierra
#

If one can't copy files in/out of Persistent data path easily then what is a good place to dynamically store assets at runtime for in game reference?

shell scarab
#

I'm not so sure if the foreach loop will only loop through direct children or not however. Documentation is not clear on that.

shell scarab
flint sierra
shell scarab
#

Ik it works for windows and mac, found an answer saying it works for android, not sure about iOS.

flint sierra
#

And that will consistently get a folder in which files can easily be copied to and from on hopefully all platforms?

#

I was hopping that is what Perisitant Data path would be for me. How is it Unity doesn't have something like that baked in?

shell scarab
heady iris
#

is a specific platform not usable?

flint sierra
#

It seems I can put files in there, but I can't copy files out?

heady iris
#

no, that's dataPath

shell scarab
#

misunderstood docs lol

heady iris
flint sierra
#

Windows

heady iris
#

why do you think this?

#

it's just a folder in AppData\LocalLow

flint sierra
#

AppData/LocalLow

shell scarab
#

why can't you read files?

flint sierra
#

exactly, I don't think windows likes you touching things in there

heady iris
#

what?

flint sierra
#

but that's the default location

heady iris
#

that's where application data goes

#

go nuts

flint sierra
#

It won't let me go nuts lol

shell scarab
#

what happens when you try?

heady iris
#

then what problem are you having?

flint sierra
#

Unauthorized access

heady iris
#

sounds like you've done something very weird to your folder permissions

shell scarab
#

are you using unity on something like a school or work computer?

flint sierra
#

Nope

heady iris
#

show us the error you are seeing.

flint sierra
#

Just trying to use the File.Copy command on a file in there

#

1 sec

shell scarab
#

unauthorized access can also be thrown if you're trying to read/write from a directory and not a file

heady iris
#

yes

#

or if you're trying to write to a bad place

flint sierra
#

what's a bad place?

#

Failed to copy media file with error: Access to the path 'C:\Users\me\AppData\LocalLow\Comp\TheApp\ImportedContent\TV' is denied.

heady iris
#

and is TV a file or an entire directory?

shell scarab
flint sierra
#

TV is a directory

shell scarab
#

then yea you can't read or write to a directory

heady iris
#

iterate over the files in it and copy them individually

shell scarab
#

you need to create a file in the directory and read/write from there

flint sierra
#

ah

#

Ok

#

silly me

#

Its File not Directory...

#

Yup that did the trick. Windows could be a bit more specific in regards to why something is unauthorized but thanks folks

heady iris
#

yeah, it's a bit unintuitive

#

you see similar errors on other platforms, too

hard quiver
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

hard quiver
#

trying to make shooting code for tank game, line 54 "tankColliders" error saying about Collider2D not def.

shell scarab
#

what's the exact error?

hard quiver
#

Assets\scripts\Shooting.cs(54,42): error CS1579: foreach statement cannot operate on variables of type 'Collider2D' because 'Collider2D' does not contain a public instance or extension definition for 'GetEnumerator'

shell scarab
#

also, I see immediately you could probably do this better if you stored round as the type Round not GameObject so you do not need to call .GetComponent on it.

#

oh. tankColliders is not an array.

hard quiver
#

well im just starting and some of the lines are copied

#

and some i added myself

shell scarab
#

i see

#

well tankColliders needs to be an array, not single object. It's like you're saying for each apple in my apple, instead of saying for each apple in my apple container.

hard quiver
#

original code had "[]" in line 12 after Collider2D

shell scarab
#

yes, that makes it an array

hard quiver
#

but it generated error in line 25

#

by deleting it i got rid of the line 25 error and kept going

shell scarab
#

yes, because that is getting a single component, not multiple components. I believe instead of iterating through a foreach statement, you should set the bullet's layer and tank's layer and just say they ignore each other for physics.

hard quiver
#

ohh, so like ignore that part of the code?

shell scarab
#

although it would be in Physics2D not Physics

rigid island
hard quiver
#

on that exact 2 lines

rigid island
#

tankColliders was not able to iterated, its not collection so you needed []

hard quiver
#

it does this

rigid island
#

I get it

hard quiver
#

by deleting the array it fixes

rigid island
#

no

#

its because ur GetComponent is wrong

#

It should be GetComponents

hard quiver
#

oh

#

and suddenly everything works

#

thanks i guess @rigid island @shell scarab

#

if something breaks i will try the layers method

rigid island
#

using layer ignoring between each pieces on the tank would be cleaner than code

#

but both work fine

#

there are instances you only want to do ignoring at particular times , eg like a bullet only ignores when instantited from player but after a timer, it could potentially bounce and still hurt player

earnest gyro
#

Help with State Machines - Need to Pass Around Mutable Lists of States

river kelp
#

Does anyone have any experience with object pools for networked games? Are there any considerations I have to make with regards to activating / deactivating objects on the host / clients?

#

Like if the client clicks and spawns a pooled object bullet, I send that message to the server and have it spawn a bullet too, but I want them to spawn the same bullet

#

Or is there a network for game objects way of doing this that differs from how you'd do it in a single player game?

lean sail
river kelp
#

I'll ask there

green radish
#

can anyone explain why this always prints zero?

#

in all contexts it's being used the list is a size of 2

#

so this should only be printing when it exceeds Element 1(forceCount is being set to the list.Count in the Start method)

#

the intended purpose of the method is that it should check if the selected Element is not part of the original items in the list, if it's not one of the originals, I would proceed to remove it

#

if that works than I'd add extra conditions for when it should be removed

quaint rock
#

well if its printing 0 that suggest that forceCount was at 0

loud wharf
#

And forceCount is 0. And subtracted by 1 so it meets the condition.

spring creek
#

What is the difference between Forces.Count and forceCount? Curious how the latter is set

Edit: ah, in start

heady iris
#

you have two different values, yes

quaint rock
#

also not sure how this tests if its part of the orginal items or not

#

you never check the value of the items, just the index

lean sail
#

The debugger can explain it best, you really should use it. Itll tell you what every single variable is an even pause execution so you can take however long you want to check every variable

green radish
#

I found out the cause is that one object has a list of 1, but that still doesnt make sense, if its checking above forceCount - 1, that means it should be checking if above 0 in that context, and only printing if it has two Elements

quaint rock
#

yes but forceCount was 0

#

then you subtract one making it negative one

#

so zero is greater then negative one

green radish
#

forceCount is equal to the list.Count, which would be 1, not 0

quaint rock
#

why have it then

#

directly do list.Count

green radish
#

then it subtracts 1, which is 0, then checks if above that

lean sail
#

That is all what you think is happening. Not what is happening

spring creek
green radish
quaint rock
#

just log the value of it in the loop

#

you will see its 0

#

if something is weird, use the debugger or log to test all assumptions

green radish
#

I just found the problem, its really tiny and dumb, but it makes sense now, I forgot to include the line setting forceCount in the original class, so the object using that class directly gets a forceCount of 0

#

no object ever should be using that class under normal circumstances, but I had put it on one just to test that it works, and somehow forgot to include that line

loud wharf
green radish
#

the point is that forceCount is logging the original count of the list, that way I can check if the selected item is one of the original ones

#

if not, its safe to remove

#

so its comparing the original count to the current count and removing new items, which can then be changed to only remove them under certain circumstances(if the selected Force has a force value of 0, since that means its doing nothing)

shell scarab
#

How would I have different play modes? For example many games have something like running in debug mode or not what you can choose from an option in steam or by running it with a command line arg. It appears that I cannot read passed command line args however, so is there a way?

heady iris
#

Sounds like you want command line arguments. I'm pretty sure you just use System.Environment.GetCommandLineArgs();

quaint rock
#

yeah you can still pass it args like a regular application

shell scarab
#

Oh

#

When looking that up online it just says you canโ€™t with unity lol

quaint rock
#

make a build and test it out, use the line @heady iris suggested

#

will return a array of them, then you can check for the one you care about and act accordlining

rocky basalt
#

How could you take a AudioClip.length (float) and turn it into a string "1m10s" format?

#

I am having hard time finding way to accurate get certain decimal places

quaint rock
#

@rocky basalt it gives length in seconds

#

so could do the math and round

#

or feed it into a TimeSpan

#

and use it to get the minutes and seconds

shell scarab
#

you could also divide it bu 60 then modulo by 60 and combine that

quaint rock
#

that or a TimeSpan.FromSeconds(clip.length) then you can ask that for the number of minutes and seconds to format a string.

shell scarab
#

Does .ToString have a time formatter?

#

If it does could possibly use that

quaint rock
#

would have to test, in this case would jsut from seconds then ${x.Minutes}m{x.Seconds}s

lethal mantle
#

Can someone give me a movement script

vagrant blade
#

That's not how this Discord works.

lethal mantle
#

Then where can I go too get one

heady iris
#

now you're both cross-posting and asking people to write your code for you.

lethal mantle
#

Yes I am

#

Like I said I started TODAY

vagrant blade
#

Great, so start !learning

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

lethal mantle
#

Thank you

rocky basalt
#

Here's the float to mins/secs code I landed on

float length = audioClip.Length; string mins = (length / 60).ToString("F0"); string secs = (clipLength % 60).ToString("F1"); string finalResult = mins + "m " + secs + "s";

#

Results

ember cape
shell scarab
#

I have a scene controller (if i need it) and a global controller. I use a scene loaded callback to know when a scene was loaded to grab the scene controller from the global controller.

#

If i dont need a scene controller and global controller, i just use the callback to grab different references or whatever i need it to do

ember cape
shell scarab
#

I like to use that one bc it can also be used from any class and i get information ab the scene passed to me

half trail
#

With netcode for gameobjects how should I go about timestamping game states? I tried using the network tick system but they dont seem to line up on client and server. Like an object starts moving at tick 100 for server and tick 97 for client. Then when I run some code for reconciliation client will conpare server tick 100 with client tick 100 which will obviously be different because it shouldve checked client tick 97

#

Looking at the documentation it makes sense since localtime/servertime arent meant to be synced between clients and server if Im understanding it correctly so what should I use instead?

leaden ice
half trail
half trail
#

Oh yea I ran into pages for this while looking for timestamp stuff

#

Is there a difference between netcode for gameobjects and netcode for entities?

leaden ice
#

yes

#

one is for GameObjects

#

one is for ECS

half trail
#

Sorry, what is ECS?

leaden ice
#

it's basically a revamp of the whole engine to not use GameObjects and components, but rather use a different system which is more efficient in terms of memory layout and multithreaded by default

half trail
#

I see

#

How difficult would it be to convert what I have currently to support ECS?

leaden ice
#

very difficult

#

It's not something you do lightly

spring creek
#

Basically always do it from the start. I converted once and... i'm still doing so

half trail
#

Just wanted to use netcode for entities for the client side prediction I suppose

leaden ice
half trail
#

Yea its been on the roadmap for a while

leaden ice
#

You could look into Photon Fusion

#

they have SA/client prediction/lag compensation

half trail
#

Yea I tried PUN first but I switched to NGO since that was the unitys implementation

leaden ice
#

PUN is not Fusion

half trail
#

Oh

leaden ice
#

PUN is a much older much shittier framework

half trail
#

I see

leaden ice
#

(both are products of the company called Photon)

half trail
leaden ice
#

third solution is implement your own

half trail
#

Yea thats what Ive been trying to do

leaden ice
#

yeah sorry I sidetracked you because I didn't realize they didn't have an implementation yet

half trail
#

No worries!

#

These all look like fun rabbit holes to look into in the future

#

Especially ECS

half trail
spring creek
half trail
#

Might wait on that for now

#

But it seems like localtime.tick isnt what Im looking for to timestamp gamestates

#

Would I have to sync up a counter or something?

versed zodiac
#

I refactored some code around to instantiate tilemaps on demand as opposed to having them sitting in the scene. Now I'm suddenly getting an error every time I run the project:
"In order to call GetTransformInfoExpectUpToDate, RendererUpdateManager.UpdateAll must be called first.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)"

Google has plenty of results but no real answers. Unity claims to have solved the issue in a previous version, but that isn't the case. I'm using 2023.1.3f1.

How do I hunt down the fix with an error message as vague as that?

#

Weirdly, I've noticed it has something to do with the tilemap as a whole coming into the camera's view. If I run the project with the tilemap out of view, no error, but as soon as it moves into view, error.

cosmic rain
# half trail Would I have to sync up a counter or something?

Maybe look at solutions similar to GGPO and how they're implemented. Fro what I understand, there's a certain sync point, where you definitely know that the clients are in the same state, where you would start a frame counter and do your roll acks based on each clients current frame.

leaden ice
versed zodiac
#

I should clarify that this is happening with the 2D URP.

thin shoal
#

It there a way to have custom skins on characters like Additional clothing to a model without inserting such object into the model itself?

whole mist
#

is there a reason why my enemies are not repathing when this is called?

#

both the agent and the target are prefabs

#

i feel like it might have something to do with that but im not sure

shell scarab
#

Is there a way to make this unchecked properly? Getting an oveflow exception from it.

#
ulong longSeed = unchecked(ulong.Parse(step2)); // step2 is a string
#

also tried this:

#
ulong longSeed = unchecked((ulong)BigInteger.Parse(step2));
cosmic rain
cosmic rain
#

Though I'd really avoid doing that. If the overflow is inevitable, just catch the error and handle it.

#

You don't want undefined behavior running wild in your app.

shell scarab
shell scarab
cosmic rain
cosmic rain
#

Or both. But you're not wrapping the assignment in unchecked.

cosmic rain
#

For example, if you build IL2cpp build there's no guarantee that an overflow would work the same way.

shell scarab
#

hmm.

thin shoal
#

not so much guides on how to do them as well

cosmic rain
thin shoal
#

the model have Weight paint and should be flexible

shell scarab
thin shoal
#

now it just disappeared

cosmic rain
cosmic rain
# shell scarab I believe overflow behavior is defined btw:

It is defined in C#, but it's still erroneous behavior. Besides, it seems like you don't understand how it works exactly - you assumed that it would reset to 0.
That's why it's better to catch the error and handle it instead of hiding it with unchecked.

thin shoal
#

ok but the model is stiff and does not follow the character

shell scarab
#

it even says right thre that it wraps around from the maximum value to the minimum value

thin shoal
#

and made the source object disappeared

cosmic rain
shell scarab
#

i believe in this situation it would be fine: I'm taking a user's string and converting it to a bunch of numbers, which can be really big. I don't care exactly what the numbers are, just that it's the same each time. I'd be using it for a seed.

#

for now I'm just using BigInteger but it was annoying that unchecked doesn't work for casting.

cosmic rain
shell scarab
#

i believe it definitely is fine

cosmic rain
#

Well, suit yourself then. If this kind of code was in a project I'm working it I would tell them to rewrite it.

shell scarab
#

why??

cosmic rain
shell scarab
#

if zzzzzz goes to idk, 46 each time, why care? It's the same each time for zzzzzz, and that's all that matters is that it produces the same value for the same string.

thin shoal
#

Tested on blender using the same model imported via fbx

cosmic rain
# shell scarab why??

Because stuff like user input can produce a plethora of errors, some of which you'd want to catch and handle in different ways.

#

It's not about wethet it works in your case or not. It's about good and bad practices. It's like using static field for player variables in a single player game. It would work, but no one would suggest that kind of code.

shell scarab
#
        string step1 = Regex.Replace(seedString, @"[^a-zA-Z0-9]", x => "");
        string step2 = Regex.Replace(step1.ToUpper(), @"[a-zA-Z]", x => ((int)x.Value[0]).ToString());
#

I believe this would work for every case

cosmic rain
shell scarab
#

sorry, I just really don't see where the problem is

cosmic rain
shell scarab
#

I want to allow letters and just turn them into numbers.

cosmic rain
# shell scarab yea, by not allowing % for example be put in?

I don't know anymore. If you want to allow letter and turn them into numbers(not sure how you're gonna do it), it's up to you.

I've made emy point: you should be handling errors instead of hiding them. If you want to ignore it, feel free. There is no point in continuing this discussion.

shell scarab
#

but how is behavior that seems to be defined an error!? It's a keyword, they don't just make features to hide errors.

#

well whatever

shadow laurel
#

I keep encountering this Null Reference Exception (Attached Image), but can't seem to find the problem in the code (Linked below). Could I get some help with this
https://hatebin.com/jjjlyjnkea

cosmic rain
shadow laurel
#

line 51 is the if (character.IsOwner) statement

#

the only other code I have written is the lines relating to the WorldSaveGameManager, or the TitleScreenManager. Which have been working until I wrote the script linked

cosmic rain
shadow laurel
#

I'll check that and see if I can fix it from there thanks

cosmic rain
#

If you have issues like that it's really too early for you to do networking. I recommend reevaluating your priorities and maby have a few single player games finished first.

shadow laurel
#

Nah, its alg. I just hadn't encountered that before and the error had a lot in it so I was unsure what to do. I got it fixed now though. Thanks for your help aok

vague tundra
#

How can I achieve something like the following behaviour:

I have a chain of classes that extend eachother, with the parent-most class extending ScriptableObject.
How can I have an empty list on the parent-most class, and add to that list in each extending child, such that child-most class has all the items its parents have contributed?
All classes are abstract, other than the child-most class

cosmic ermine
#

is there anyway I can tell unity to just ignore an assembly? Like not bother checking and displaying the errors from an assembly in console?

leaden solstice
cosmic ermine
# leaden solstice What errors are you getting?

valid ones. I'm making a fairly large change to the way my code is structured so the other assemblies are getting angry at not being able to find the stuff they want. So I just want to disable them temporarily so I can focus on errors in the new code only. Does this make sense? For now I'm just manually commenting out the scripts in the assemblies, but this is slow lol

leaden solstice
cosmic ermine
sharp cloak
#

Why does the obstacles list is empty on last line in scr?

cosmic rain
sharp cloak
cosmic rain
sharp cloak
cosmic rain
#

Does the loop run?

sharp cloak
#

Yes

#

It prints in The start The correct count

#

But somehow in The other void The count is 0

cosmic rain
#

Then you either have another object where nothing is added to the list, or you clear the list somewhere else.

sharp cloak
#

Thats The only code

upper pilot
#

Is it normal for onClick event to not be visible in the inspector at runtime if added through code?

cosmic rain
# sharp cloak

That can't possibly be the only code. You call that method from somewhere else, so...

sharp cloak
#

Yeah i call the method from the other file but only this one has the access to obstacles list

cosmic rain
leaden solstice
#

Iโ€™m guessing theyโ€™re referencing prefab ๐Ÿ˜„

cosmic rain
#

They iterate transform in Start. I can't think of a situation where that would be a prefab.๐Ÿค”
It could be that the ChangeObstscle is called on a prefab though.

leaden solstice
#

Yeah from the other script I meant

civic dirge
#

Can I ask for help here?

upper pilot
#

Is there a way to see if listener already exists or how many there are?
I am deleting a button object with listener on it, then creating a new one, but it seems like I have multiple listeners on the same button.

lean sail
civic dirge
upper pilot
#
public void UpdateUpgradeButtons()
{
    foreach(Transform transform in upgradeButtonContainer.transform)
    {
        Destroy(transform.gameObject);
    }

    foreach (UnitSO unitSO in UnitsDB.Instance.unitsList)
    {
        UnitData unitData = PlayerUnitData.Instance.GetStats(unitSO);
        UpgradeButton upgradeButton = Instantiate(upgradeButtonPrefab, upgradeButtonContainer.transform);
        UpdateUpgradeButtonText(upgradeButton, unitSO, unitData);

        upgradeButton.GetComponent<Button>().onClick.AddListener(() => SelectUnit(upgradeButton, unitSO));
    }
}
#

Is there anything that might cause listener to be added to the same button twice?(or 5 times? :D)

#

I am destroying the object before I create new one.

civic dirge
#

I have two layers of inheretance in my prodject, all of them uses the start function, is there a way to call the middle one, cause base.Start goes down to the first one?

leaden solstice
civic dirge
#

wierd, maybe something else is happening

leaden solstice
#

Make sure you are using virtual/override Start

civic dirge
lean sail
upper pilot
opal cargo
#

Hi guys, does someone have a good resource (or two) about how to organize animation, movement, camera, input and game states?
My state machines for PlayerController, CameraController and WeaponController are quite huge and need to observe each other for state transition, that's getting a bit complicated. When putting UI like a pause menu on top or starting to change animations depending on the PlayerController-State, it slowly falls apart. Are there some interesting GDC talks to see some best practices by huge studios for player control and flow?

covert turret
opal cargo
#

To communicate between Cam, Kinematic Character Controller and Weapon Controller I use simple C# events

#

Looks kinda like this

#

When my Kinematic CC detects it's i.e. on a slope, it sends an event to the cam (via Player Controller) to limit camera rotation so that the Player always looks down the slope

covert turret
#

sounds good so far, what do you mean by things fall apart exactly?

#

If you put a pause menu can't you deny all the events from triggering via player controller?

#

if everything really routes through there

opal cargo
#

At the moment my FSM in the KCC also triggers the animations depending on the state of the Character, but this also effects animation (sliding animation, walking, etc.). But i.e. my Weapon Controller also triggers some animations which can interfere with the KCC

covert turret
#

sounds like you need an animation queuing system of some kind

#

so they're overriding each others animations?

opal cargo
opal cargo
#

Also I don't know if this is best practice, so I want to learn how most studios do Controllers for Movement, Animation, Camera etc.

#

And how they work together, what patterns they use

covert turret
opal cargo
#

I have an input class that gets all events from unity input system and sends out events to subscribers

public class InputReader : ScriptableObject, PlayerInputMap.IGameplayActions, PlayerInputMap.IInventoryActions, PlayerInputMap.IUIActions
{

    PlayerInputMap _gameInput;

    private void OnEnable()
    {
        if(_gameInput == null )
        {
            _gameInput = new PlayerInputMap();

            _gameInput.Gameplay.SetCallbacks(this);
            _gameInput.UI.SetCallbacks(this);
            _gameInput.Inventory.SetCallbacks(this);

            SetGameplay();
        }
    }

    public void SetGameplay()
    {
        _gameInput.Gameplay.Enable();
        _gameInput.UI.Disable();
        _gameInput.Inventory.Disable();
    }

    public void SetUI()
    {
        _gameInput.Gameplay.Disable();
        _gameInput.UI.Enable();
        _gameInput.Inventory.Disable();
    }

    public void SetInventory()
    {
        _gameInput.Gameplay.Disable();
        _gameInput.UI.Disable();
        _gameInput.Inventory.Enable();
    }

    public event Action<Vector2> MoveEvent;
    public event Action<Vector2> LookEvent;

    public event Action JumpEvent;
    public event Action JumpCancelledEvent;
....
wintry crescent
#

if, in Awake, I disable that script and then enable it, will it call OnEnable twice and OnDisable once, or will it call onEnable once? Will onEnable and onDisable happen immediately when enabling/disabling the object, or only after Awake is done?

covert turret
#

You've got the right idea with the hierarchy, as long as you're able to be modular without interdependency between classes you're on the right path

#

But yeah there should be a sort of 'game manager' that controls the state of the game, you could technically stick it into the input reader like you did there, but that is breaking single responsibility

#

states could look like:
Menu
Game
Cutscene

#

or not at all, you could just go straight boolean and check if user is in a menu or not

opal cargo
covert turret
#

I do want to comment that the tree you have for the player controller is really good though

opal cargo
#

The thing that bothers me the most is the following

#

Find it awkward that my Hand FSM can set a KCC State like this, maybe I should move all state change logic to Player Controller instead and control every state from there (Cam, KCC, Weapon)?
Then PlayerController has to read all necessary state information from KCC though, since KCC checks for grounded etc.
But this would bring more dependencies I guess, what shouldn't be an issue when my Player Controller is written for the KCC, Weapon Controller and CamController?

#

Aaaand I think I'm getting into an analysis paralysis ๐Ÿ˜„

covert turret
#

If I'm interpreting this corrrectly, then yes it looks fine. The hand will tell the controller how to react

#

and then player controller will validate to see if the action can be done

#

this is from F.E.A.R game devs

#

the animation that tells the agent to play is attached to the object

#

rather than stored in the player

opal cargo
covert turret
#

yeah

#

and the event to trigger the camera shake is sent back up player controller?

opal cargo
#

Yes, the new Body FSM state sends an event to Player Controller, which is subscribed by the camera that get's a follow Point by the event and centers the camera on the ledge, so the player always looks where he's trying to grab onto.

opal cargo
covert turret
#

its a good read

#

talks about how they designed the AI

#

plenty of FSMs

opal cargo
#

And maybe you can clarify some other thing to me, at the moment I have some special FSM States that ignore player input and just move the players XYZ position (lerp) over time while playing an animation - is this how fixed animations like climbing up a ledge are done or is there a better way?

#

Like

public class PlayerClimbSmallLedgeState : PlayerBaseState
{
    ....
    public PlayerClimbSmallLedgeState(TanukiKCC currentContext, PlayerStateFactory playerStateFactory, TanukiCam tanukiCam, Animator animator) : base(currentContext, playerStateFactory, tanukiCam, animator)
    {
        _animationList = ctx.climbUpSmallAnim;
    }

    public override void CheckSwitchStates()
    {
       if(animationDone)
        {
            ctx.debugState("Switching to Fall");
            CurrentSuperState.ExitState();
            SwitchState(factory.Grounded);
        }
    }

    public override void EnterState()
    {
    
        TimeInState = 0;
        _listCnt = 0;
        animationDone = false;
        animator.Play("ClimbUp");
        ...
    }

    public override void ExitState()
    {
        _listCnt = 0;
        animationDone = false;
        ctx.debugState("Exit UpForward State");
    }
    ...

    private void PlayAnimation()
    {
        if (animationDone)
            return;

        Vector3 animation = new Vector3(
            diff.x * _animationList[_listCnt].Z.Evaluate(TimeInState / _animationList[_listCnt].AnimationDuration),
            diff.y * _animationList[_listCnt].Y.Evaluate(TimeInState / _animationList[_listCnt].AnimationDuration),
            diff.z * _animationList[_listCnt].Z.Evaluate(TimeInState / _animationList[_listCnt].AnimationDuration)
        );

        ctx.motor.SetPosition(startPos + animation);

        if (TimeInState <= _animationList[_listCnt].AnimationDuration)
        {
            return;
        }

        if (_listCnt < _animationList.Capacity - 1)
        {
            _listCnt++;
            TimeInState = 0;
        }
        else
            animationDone = true;
    }

    public override Vector3 UpdateVelocity(Vector3 currentVelocity, float deltaTime)
    {
        TimeInState += deltaTime;
        PlayAnimation();        

        return Vector3.zero;
    }
}
#

So there are some XYZ-Curves that specify how the player moves to the desired position over time, while this is done an animation is played in parallel.

#

Maybe I can replace this whole thing by AnimationClips and Keyframes?

ashen yoke
covert turret
#

Personally, I wouldnt be too concerned how 'good' an implementation is until it needs to serve a purpose that I completely had no foresight of it needing. Otherwise you'll fall under the same category as premature optimisation

#

If it works, it works, until its too clunky and heavy to work with

ashen yoke
#

well you can write everything in a single static class using goto instead of methods

opal cargo
ashen yoke
#

then refactor to use methods

covert turret
#

You could also just replace it with an animation with root animation? But you chose to do lerp

ashen yoke
#

then refactor to use classes

covert turret
#

Yeah well thats where wisdom from experience comes in

ashen yoke
#

and so on, or you can simply select a good architecture from the start

covert turret
covert turret
#

just to pursue the 'better' system

opal cargo
# ashen yoke does your fsm have transitions abstracted?

No, I just use a base state and working with Root and Substates

public class PlayerClimbState : PlayerBaseState
{
    ...
    
    public PlayerClimbState(TanukiKCC currentContext, PlayerStateFactory playerStateFactory, TanukiCam tanukiCam, Animator animator) : base(currentContext, playerStateFactory, tanukiCam, animator)
    {
        isRootState = true;
        _animationList = ctx.climbUpAnim;
    }

    public override void CheckSwitchStates()
    {
        if(!ctx.inputs.wantClimb && !isAnimating)
        {
            SwitchState(factory.Fall);
        }
    }

    public override void EnterState()
    {
        ...
        InitializeSubState();
    }

    public override void ExitState()
    {
        ...
    }

    public override void InitializeSubState()
    {
        if(ctx.inAir && !ctx.onWall)
        {
            ctx.onWall = true;
            Debug.Log("Set onWall");
            SetSubState(factory.ClimbHangOnAir);
        }
        else if(ctx.inputs.moveInput.x != 0 )
        {
            Debug.Log("Set ClimbSide");
            SetSubState(factory.ClimbSideway);
        }
        else if(ctx.inputs.moveInput.y > 0 && CheckClimbUp() && ctx.onGround && smallLedge)
        {
            Debug.Log("Set ClimbSmallLedge");
            ctx.isClimbing = true;
            SetSubState(factory.ClimbSmallLedge);
        }
        else if(ctx.inputs.moveInput.y > 0 && !ctx.onWall && ctx.onGround)
        {
            Debug.Log("Set ClimbUp");
            ctx.onWall = true;
            SetSubState(factory.ClimbUp);
        }
        else if(ctx.inputs.moveInput.y > 0 && ctx.onWall && !ctx.onGround && CheckClimbUp())
        {
            Debug.Log("Set ClimbUpForward");
            SetSubState(factory.ClimbUpForward);
        }
        else
        {
            Debug.Log("Set ClimbIdle");
            SetSubState(factory.ClimbIdle);
        }
    }

    public override void UpdateState()
    {
        CheckSwitchStates();
    }
...
}
ashen yoke
opal cargo
opal cargo
ashen yoke
#

hierarchical just implies nesting, afaik, it doesnt specify what method is used for state change

covert turret
#

Depends on your situation

ashen yoke
#

in your case your states are allowed to manipulate fsm state

#

meaning they break encapsulation and the whole thing is hardcoupled to specifics

#

if you abstract the logic for state switching into transitions the states will need to know a lot less

#

states will only implement their direct function, setting parameters, speed etc,
while transitions that are injected into fsm at higher level will dictate and make decisions on how the fsm as a whole works

opal cargo
# ashen yoke if you abstract the logic for state switching into transitions the states will n...

So more like in my simpler FSMs?

_drawState = new BowSimpleDraw(this,_animator);
_loadState = new BowSimpleLoadArrow(this,_animator);
_idleState = new BowSimpleIdle(this,_animator);
_switchState = new BowSimpleSwitch(this,_animator);
_pullState = new BowSimplePull(this,_animator);
_shootState = new BowSimpleShoot(this,_animator);

void At(ISimpleState from, ISimpleState to, Func<bool> condition) => _BowSM.AddTransition(from, to, condition);
Func<bool> DrawToLoad() => () => _drawState.AnimationDone;
Func<bool> LoadToIdle() => () => _loadState.AnimationDone;
Func<bool> LoadToSwitch() => () => CurrentArrowType != _nextArrowType;
Func<bool> IdleToSwitch() => () => CurrentArrowType != _nextArrowType;
Func<bool> SwitchToLoad() => () => CurrentArrowType == _nextArrowType;
Func<bool> IdleToPull() => () => _holdPrimFire;
Func<bool> PullToIdle() => () => !_holdPrimFire;

At(_drawState,_loadState, DrawToLoad());
At(_loadState,_idleState, LoadToIdle());
At(_loadState,_switchState, LoadToSwitch());
At(_idleState,_switchState, IdleToSwitch());
At(_switchState,_loadState, SwitchToLoad());

At(_idleState,_pullState, IdleToPull());
At(_pullState,_idleState, PullToIdle());
ashen yoke
#

this is so verbose im failing to parse

#

i guess

#

this is an example i keep bringing up

opal cargo
#

Ouh, Behavior Trees

ashen yoke
#

but you dont have to go far

#

the unity animator is a fsm in a pure sense

#

transitions etc are objects, with conditions, params are objects

#

everything is abstracted

opal cargo
#

Boy that escalated quickly ๐Ÿ˜„

ashen yoke
#

i wont bring its api because its fubar, but in general its a good example

opal cargo
#

Hmm, will take a look as well

#

Are there any GDC talks you can recommend for my how player components work together best practice thing?
Still feel I can make this simpler to use. Already have over 10.000 lines of code just for Kinematic CC and Camera o.O

ashen yoke
#

if i seen some i wont remember which ones

opal cargo
#

Anyway, thanks to @covert turret I already know that my implementation isn't so wrong and thanks to you I will look into the FSM stuff again a bit deeper.
Do you have any recommendations for animations and movement? Think I'm lacking experience there and getting to a point, where this is valuable.
Next I want to implement some Bow mechanics and see how I can combine walking and Bow usage...

ashen yoke
#

in my view detaching the transition from states is the basis of most ai systems, fuzzy logic, utility ai, bts, goap

#

most differ just in the way transitions are implemented, utility selectors, pathfinding for goap

covert turret
opal cargo
opal cargo
#

For now I just import some mixamo animations and play them in my Root-States with some Blending for moving left/right/front/back

covert turret
#

yeah, animation is a whole different area

opal cargo
#

And also I have to learn how to couple my first person camera with those animations, seeing the skull of my character is distracting ๐Ÿ˜„

#

Some nice tutorials for this topic at hand? Just to get an overview

gray mural
#

what is the best way to make a script that allows you to stretch a ui panel?

#

I have a method that returns a vector that shows if panel can be stretched. E.g. (1, 0) is right stretch

#

do I have to store previous mouse position to find mouse direction?

ashen yoke
#

store initial mouse click, each frame you get delta from it

#

adjust size based on that delta

gray mural
ashen yoke
#

no, initial vs current will give you distance from start of drag

covert turret
# opal cargo Some nice tutorials for this topic at hand? Just to get an overview

Learn how to animate characters in Unity 3D with dynamic animations from blend trees!

This beginner-friendly tutorial is a complete walkthrough of two dimensional blend trees and how we can use blend trees to create new animations for our characters using two float parameters!

ACCESS PROJECT FILES & SUPPORT THE CHANNEL:
๐Ÿ’› https://www.patreon.c...

โ–ถ Play video
ashen yoke
#

you need to keep the initial position as a point of reference

covert turret
#

goes in depth with the functionality for everything without being a bore

gray mural
ashen yoke
#

or rather, the initial offset

gray mural
#

player can make a panel both bigger and smaller

#

so initial offset won't help here?

covert turret
#

why not? you can find the difference in size

#

with initial offset

ashen yoke
gray mural
ashen yoke
#

where A initial offset, orange is after mouse move, red is the total vector used to adjust size

gray mural
#

it's not the same as moving a panel

ashen yoke
#

current - initial

gray mural
swift falcon
#

making my own vector struct and curious why this is giving a compile error ref Vector biggerVec = vec1.size > vec2.size ? ref vec1 : ref vec2;
when it lets me do something like ref Vector biggerVec = ref vec1;

gray mural
#

mouse position?

ashen yoke
#

current offset

#

which is mouse position + initial offset

#

(current position + initial offset ) - (initial click + initial offset)

gray mural
#
Vector2 offset = new Vector2(.1f, 0f);

_rect.sizeDelta = _rect.sizeDelta + offset;
_rect.anchoredPosition = _rect.anchoredPosition + offset / 2f;
ashen yoke
#

that you cant ref in that scope?

gray mural
swift falcon
ashen yoke
#

try decomposing that whole ternary into an if block

#

it will probably explain why it doesnt work

gray mural
ocean river
#

ay
is there some download for Cinemachine supported on 5.6/2017?
yes, im locked on that ancient version, i can not upgrade.

Please just provide me with an download link, thanks.

scarlet viper
#

is it wrong to make small velocity adjustments by modifying velocity directly, if i also want the thing to work with AddForce() ?

leaden ice
knotty sun
# ocean river ay is there some download for Cinemachine supported on 5.6/2017? yes, im locked ...

Add schematic nodes forย Cinemachineย support with this plugin. Adding the Plugin Before importing the plugin into your Unityยฎ project, make sure youโ€™ve got Makinom and Cinemachine imported in it. Youโ€™ll need at least Makinom 1.9.1ย and Cinemachine 2.2.8 to support the plugin (for versoin 2.0.0, for version 1.0.2 use the latest version in the Asset...

scarlet viper
#

not touching X and Z

#

nevermind i confused the axes because i havent coded it yet but the purpose of it is to make it stop flipping

severe sable
#

Anyone know how I should go about creating an attachpoint system that allows blocks to be attached in a snap grid style system? I am wondering how to implement this without having to do tons of percision editing of each new prefab of a block or shape.

#

I have streamlined much of my block implementation system, to make it simple for me to add new content, I've done this prior with many abstract classes, maybe it would be worth making classes for each shape with predefined attach points? That is the best solution I can think of, but if anyone has any other ideas do tell!

steady moat
leaden ice
#

assuming they're not just at regular grid intervals..

agile elbow
#

why after watching testing 10 ads, the PC starts to froze?

severe sable
# steady moat Ideally, each block will perfectly fit the allocated space it is in. In other wo...

How could I do this with fancy sprites though, like lets use an antenna dish for example, there may be a flat surface to connect on the bottom, but on the sides and top, we wouldn't want attachpoints, however on the other hand I don't want blocks to be limited to cubes entirely, since I know players love making asthetically pleasing designs and that is quite hard with too simple geometry

severe sable
leaden ice
#

You can also use prefab variants to cut down on the amount of work if you have for example many blocks with the same shape but different skins or something

steady moat
leaden ice
#

anyway if not done manually, you'd have to establish some rules about how it works

severe sable
#

Lets say maybe a hundred or so, but I want to allow for players to add their own and for me to add new content easily, its the best buisness practice to let players make their own content

steady moat
#

And, people can still mod your game same if you do nothing.

agile elbow
#

why after watching 10 testing ads, the PC starts to froze?

steady moat
agile elbow
#

I just want an answer...

steady moat
#

Nobody knows what is your issue.

agile elbow
#

at least do u know how to switch from that 10 seconds unity ads videos, to an actual ad from a game?

steady moat
#

Ask in appropriate channel. This is the code channel.

#

Also, there is probably a forum for that.

#

And a documentation for sure.

agile elbow
#

is here a unity ads channel?

steady moat
severe sable
# steady moat It is not really the "best business" practice. In fact, I think it is a terrible...

Fair enough It's probably opinion based, but considering I'm a one man band, it's a pretty good idea to allow for players to create content themselves as everyone benefits from that, they get to express their creativity, and enhance the experience for other players, and I don't need to devote ludicrous amounts of time to adding trivial features and can focus on making the core gameplay loop and mechanics better and more engaging

thorn glade
#

so i have an Item script

#

with a hitbox, pickup, trigger and all that stuff

#

but i want to easily be able to change what every item does

#

so i dont have to make SwordItem, PickaxeItem, BoxItem

#

instead

#

i want to be able to write functions in the inspector

#

or just call a function to another script

scarlet viper
#

if i raycast from the top to the bottom, and hit a plane with default rotation, then will the normal of that hit be (0, 1, 0) ?

thorn glade
#

is default (0,0,0)?

prime sinew
prime sinew
thorn glade
#

not an interface

#

more of firing a function to another script when a function is fired

#

or a method

#

are they the same thing?