#archived-code-general
1 messages ยท Page 183 of 1
It basically stores game data and tells the save game class to save it to file. Why divide it?
You should have a SaveManager then.
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)
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?
I'd rather not have multiple singleton classes
You can use the ServiceLocator pattern then.
As your game grow, you will need to separate the different concept. Otherwise you gonna struggle with keeping your code tidy and simple.
I'll look into it. Thanks
help pls
You need to add the body of the method.
Like:
{
Stuff your method does;
}
WTF
but thanks
Ok, I don't know
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?
something like that, i think most of that takes place in the EventSystem and InputModule components in your scene which call a "raycast" method to find what's beneath the cursor
that makes a lot of sense actually. Definitely gonna look more into the event system stuff, thank you
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 ?
Screen.GetDisplayLayout is unity's method. If you want to use it somewhere,just type Screen.GetDisplayLayout(yourList);
It can be something like this:
var displays = new List<DisplayInfo>();
Screen.GetDisplayLayout(displays);
I'm trying to create a system to move the window with the keyboard similar to that game "windowframe" but I'm not succeeding at all, do you understand any of this?
It is not possible to see UnityEvent or AnimationTrigger reference out of the box
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)
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.
Rider's Unity integration will tell you this information
not sure about VS
no, if it's disabled, OnEnable will not run
perhaps you have another instance of the script in the scene that is enabled
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.
That was my initial though also. It it also happened with another script I have too. There is something strange going on.
that means they are different instances
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)
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.
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
@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.
Sorry if this is a stupid question where do I find functions in unity document or something like that
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#.
See above, accessing the user.dll to resize the window.
oh ok i'll take a look at that very thanks
@leaden ice i thought it was a table
It's definitely uncharted, unsupported territory though!
I'm not sure I understand what you're talking about.
yes that is part of the scripting reference which I linked you above
Sorry
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
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?
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
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
If I understand correctly, you're looking for a math function for a jump such that f(0) = 0 and f(1) = 0 ?
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)
where f = movePoint.transform.forward right?
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?
yeah that's it
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?
are you using assembly definitions?
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 )
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
that's roughly what I'm looking for but X and Y could easily be X Z or Y Z or Z Y etc. it'd be easier to show you what I mean. This is what my character does in game.
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
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
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
Can't remove ParticleSystem because CFX_AutoDestructShuriken (Script) depends on it
Does anyone knows why is this error prompting?
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
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);
yeah you're destroying the ParticleSystem component instead of the whole gameobject
so what should i do?
i should paste that destry code where the object is actually being destroyed?
no, you should destroy impact.gameObject instead of just impact since that is just a reference to the ParticleSystem component on the instantiated object
MuzzleFlashVFX.Play();
ParticleSystem impact = Instantiate(shootEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impact.gameObject);
?
@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
Sorry I had to go.
Well then I guess you could do t * x - t * (t-1) * y ? Where x and y are the axis (so transform.forward and transform.up I guess)
!collab ๐
We do not accept job or collab posts on discord.
Please use the forums:
โข Commercial Job Seeking
โข Commercial Job Offering
โข Non Commercial Collaboration
ok :/
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...
thats cause VSCode is inferior to VS so I'm not surprised that feature is half broken

if you want to do some proper coding , consider a much better ide like Visual Studio @lucid wigeon
intellicode alone makes it worth
I have it... let me have another go at it...
alr. many people don't turn back once they do
make sure its configured for unity if you did not do that
so you get the full benefits
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
Can't you just click on NewMethod, hit F2 and rename it?
Does visual studio automatically give you the rename prompt?
so apparently I have the community edition which doesn't even have CodeLens with usages of methods...
I can "just" even type it manually ๐ In normal IDEs that's a one step process...
So in other IDE's it opens the rename field as soon as you extract the method?
in Jetbrains last time I checked that's how it works
so that you can choose a name for the new method instead of setting it to "NewMethod"
That does make sense, never crossed my mind though
https://code.visualstudio.com/docs/editor/refactoring#_extract-method apparently this is how they describe it works, so maybe it's a bug if it's not just me
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#.
? that was about code lens I mean something like this
I'll have another go at it in some time, but for now VSCode works for me, debugger works, extensions work
that is codelense no?
Yeah but looks like VSCode
Yeah don't mind the VS fanboys hating on VSCode :)
It recently got the official extension support back
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
Yeah, call us fanbois, VS just works and VS Code just doesn't work, no contest
Worked fine for me 6+ years ๐
and that says exactly what for some one starting to use it now?
Not sure what your point is
my point is you have 6+ years experience using VS Code, you cannot compare that with someone just starting out
You said it doesn't work. I'm saying it has been working without problems for me. That's all, Steve
to be fair the intellicode / is kinda dogshit on VSCode
How so?
VS Code as is does not work for Unity development if you are a new beginner. That clear enough for you
It's not beginner chat, and the person said they have used it without other problems than this minor one where it doesn't automatically let you rename an extracted method
Why are you talking about beginners
where's the guy that always butts in saying rider is better than both of them
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
Equally why are you talking about someone with 6+ years experience using it as if everyone has thah?
thats like every Rider user I know :X
it is ๐
You're missing the point, I'm not talking about experience, I just said I didn't have any real problems with it for 6 years
Maybe you're unlucky or I'm lucky then lol
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
Guess what, I have VS, VS Code, Rider and other IDE's, out of preference for functionality I chose VS 90% of the time
Yeah I would agree with that. Though Michael is already using VSCode without problems so its not relevant here
fair enuf ๐
It's been a while since I had to actually set up VSCode from the ground up
do somone know how i can change the parent of ui image trough script?
Not sure how big of a hassle it is nowadays
the new extension is a godsent tbh but its still not 1.0 and its a hit or miss for ppl to get working (eg it works on my windows, but on my mac it doesnt , same steps)
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 ๐"
I see
transform.SetParent
thanks
google exists, you know
ok
this should be in #archived-code-advanced
/jk
i will search the next time
except I'm not sure what a trough script is
that's only a small part of the error message
haha a long, narrow open container for animals to eat or drink out of.
says google
slot1.transform you mean
Transform parents have to be Transforms.
pay attention to the types involved
also ur error isn't underlining u might wanna configure ur editor
!vscode
so much for 'searching next time' look at the Transform.SetParent documentation
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?
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?
highly depends on the game
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
unlrelated but do consider using .CompareTag instead of that .Equals for the string
Debug.Log(collision.gameObject.name)
find out what ur actually hitting first
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)
ah yeah was gonna say that but Idk ur game lol
could be on purpose for all i knew ๐
are you using assembly definitions?
It does seem like an asmdef thing
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
Before we spend some time resolving this issue though... can you answer this?
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
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
Any help would be greatly appreciated :)
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
anyway looks like they have this and you can inherit from their gun types if you want to do tings when the guns are fire:
https://cloudwalker2020.github.io/HurricaneVR-Docs/api/HurricaneVR.Framework.Weapons.Guns.HVRGunBase.html#HurricaneVR_Framework_Weapons_Guns_HVRGunBase_AfterFired
i don't really know what this question is asking tbh
it looks like they have an examples scene though: https://cloudwalker2020.github.io/HurricaneVR-Docs/manual/intro.html#examples-scene
And you can probably look at that for examples of how to do things when guns shoot, for example
but 99.999% does not require modfying the source code of the asset in any way
It looks like all the guns provide unityevents like this:
https://cloudwalker2020.github.io/HurricaneVR-Docs/api/HurricaneVR.Framework.Weapons.HVRRayCastGun.html#HurricaneVR_Framework_Weapons_HVRRayCastGun_Fired
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
i need help when i try to do Destroy game object it doesnt disappear on my game veiw
You need to show your code at least
dont cross post
tbh im not to sure what is going wrong
Are you sure that it is even finding those objects?
Put some Debug.Logs and find out
Btw, ToList() is not needed here. Use the array and change .Count to .Length
ok
Are you doing this in edit mode perhaps? Or play mode?
wdym edit mode
When the game is not playing
this is a breakpoint
no
the game is playing
AND WHEN I CLICK THIS
caps
and then this bit of code gets run
Well, it should work, not sure what's wrong with your setup.
if you click it again, do you see an empty list in that method?
yes
it menas its deosnt acc get deleted
when u delete the parent game object does the children not delete with it?
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?
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
show the full stack trace for this warning?
that's in his resetMap method, where he news up a NewGame before using Find
ive fixed
it
the game abject where spawning their own object
but that object wasnt gettign destroyed
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?
one option is to create a copy of the SO in the editor
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
e.g.
void Awake() {
#if UNITY_EDITOR
mySo = Instantiate(mySo);
#endif
}```
i guess it doesn't die if you stay in the same scene because, even outside of play mode, the SO is being referenced
What does Instantiate do here? I googled it and yeah, google is worthless now
just...consult the unity documentation
I DID
Two lines
it's purple, because I have clicked that link many times
That's not the page I got
what search term did you use
^
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.
Do I have to Instantiate mySo every time I load a new SO into it?
As in, if I set mySo = Another_SO, is mySo Another_SO or a Instantiated copy?
an assignment doesn't instantiate the SO
x = y; just means that x and y reference the same thing
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?
well, if you assign an instance that's from an asset, yes
ugh yeah. Silly me thought the SO on disk would be read only.
well, it is.
It is, just not in the editor
In the editor, the SO gets loaded from the asset when you load the scene
yeeeeeah
The scene never unloads if you keep it open in the editor
When you restart the editor, the asset gets loaded from disk again
that's similar to what I do I believe. I load my DDOLs in a bootstrap scene, go to the main menu, then from the main menu let the player click play then go into the game scene. Sometimes if a level is big enough I split the game scene into multiple, usually in somewhat of a chain.
(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
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.
I would stop worrying about what is "fast"
I was told if you save, it'll save. And I spam Ctrl-S without thinking
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.
I know how to write code, yet I am not very familiar with Unity API yet. And I do need to worry about how fast something is due to how demanding the thing is I am making
what do you mean script properties?
this is a general C# question though, not Unity
look, I'm not trying to be rude here -- but if you don't know that private isn't a security feature, you need more experience first
if it helps @rocky helm, properties are treated as methods.
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
i'm using tons of (virtual) properties in my game now and I really need to go profile that
Well at least I feel less silly now
I coded in other engines where there was no private nor public really so I haven't had enough time to completely understand them, but anyways. seems that properties, or whatever they are, are slower.
yea but like, really not by much
what language does not have scope?
Basic?
yes it does
When you say DDOLs, do you leave the scene loaded no matter what? Like you load other scenes additively?
Luau
access modifiers, not scope
JS certaily does
don't destroy on load objects:
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
access modifiers are scope
Or atleast not used much if it exists
Lua absolutely has scope
Luau
and public/private is not related to scope
Access modifiers can influence scope.
of course they are
never heard of it but appears to be derived from Lua
which actually has scope
scope is simply the context in which a name is valid
ok you know what, fair they are related to scope for sure
I'm so used to thinking of scope purely in terms of locals
public and private aren't really used there, everything is just private, no script can just do ScriptB.variable
Anyways I don't wish to spark a fire so lets just stop please
Everything in C# is just private, unless you excplitly add public
I was under the impression that loading scenes additively does not destroy the active scenes, am I wrong?
anyway Lua isn't really an object oriented language
so the whole idea paradigm of objects doesn't really apply
Luau is
loading scenes additively combines gameobjects from both scenes. Personally I think of it as instantiating a big prefab, even though it's a bit different than that. I don't believe you specified you were loading additively.
Oh I thought that was a typo, you literally mean Luau
I'm not convinced that it is... else they might have mentioned it here https://luau-lang.org/why
I thought I did, in any case, I should DontDestroyOnLoad() my controllers just to be safe?
I believe it is, at least as far as I know what OOP is
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
Anyways it's whatever, I got the answer to my first question, I'm happy
if you need to optimize at that level imo it's really not worth saving a few nanoseconds...
I didn't know how big the difference it is, that's why I asked
I see because since I can specify to Unity to not destroy my objects, there is no point in keeping that scene active when I could just keep the objects. Is that it?
yes that is my opinion of it. Keeping that scene active is also another way to do it, but personally I find don't destroy on load to be easier to use.
And one way or another, I assume those objects are accessible by the scenes loaded afterwards?
yes
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.
How do you go about profiling that? Just comparing normal methods to virtual/override ones?
Since when this doesnt work and how to make it work?
Nothing wrong with that code
It should show up in the inspector
it doesn't sadly
it doesn't show in the inspector?
then you have compile erros
Save your file and/or fix compile errors
this is the script asset's inspector
you are looking at the script, you need to be looking at a gameobject that uses the script
on the gameobject you attatched the script to?
i see now
if you're looking for default field values, which only work in edit mode, I believe an array will work.
And is there any way i can make it apear here?
in other scripts it appears
yea try an array. But that only works in edit mode, not builds
What would work for build too?
use the start or awake method to get the references you need?
This is this is only for default references
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
will you please stop giving nonsensical advice
I'm sorry, I'm not trying to. Please explain how that's nonsensical so I can give better advice.
he is trying to see a field in the inspector, that has nothing to do with Awake or Start but is only about how it is defined in the code
i don't believe you read everything
really? #archived-code-general message
yes, really
start from here
also #archived-code-general message
total nonesense
What about how to access hierarchy from code?
in what way is an Array different from a List in the inspector?
apparently none. I suggested to try it because I was unsure how exactly default references display references in the script inspector. It takes 2 seconds to try it.
Do you mean the Hierarchy window itself through an Editor script, or the tree of some specific parent object with children?
if you read what they're asking they want the field to be assignable in the script inspector
i want to find an gameobject by name which isnt anyhow connected to the script
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
fields are never assignable in the script inspector, only once that have been attached to a gameobject
really? U sure about that?
yep
Scripts do allow you to set default values..
what's this then?
reference types that aren't an array i guess
those are assigned in the script not in the inspector
i literally showed you the inspector of a script
Yea this part
look, I assigned it
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
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.
ok,and what happens when you add the script to a gameobject?
here's a video:
Yeah it's like field initializers but from the Inspector
yup
[SerializeField] Transform obstaclesBlueprints; What type it has to be for me to be able to assign an object from hierarchy?
it just won't work if you try to instantiate an object at runtime
bc Transform and GameObject dont work
Nothing really extraordinary, but useful if you need some default asset
Any of those two
Honestly, why do you think default references exist?
how come this isnt doing anything?
https://gdl.space/coyufihase.cs
Do you have any messages, warnings or errors in your console?
!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.
also, screenshot please? Maybe you are dragging the wrong type of object?
You're probably trying to reference a scene object into a prefab, you cannot do that
this but i dont think it matters now
or a script asset
i would like to put this there
so i can access its children to form a list in Start void
sorry?
!learn
๐งโ๐ซ 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/
What are you trying to drag? Where is it located?
Same two questions for the target script of the drag-drop
Do you have this script attached to another object in the scene, or is this script attached to a prefab or another asset file that is not in the scene?
Yeah i mean i am comming back to unity after like 5 years now so i forgot everything and try to finish a project
it isnt attached anywhere, i am trying to keep this particular script this way
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
then you won't be able to do it because that's a scene object
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
if you're trying to drag it into the default reference, only assets can be assigned.
I do have a question as to why you're trying to keep the script that way?
if you want the script to grab references to things when it is instatiated, use something like this: https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html in the start/awake method
from parent
https://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html, or you can also use transform.GetChild to get the object: https://docs.unity3d.com/ScriptReference/Transform.GetChild.html
you can also use a foreach loop in this way:
foreach(Transform t in transform) {
Debug.Log(t);
}
(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?
hi did I miss something? What non mono script?
so much text now it's getting a bit lost
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
Why's that?
What type is obstacles?
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?
I believe they're trying to just assign default references in the script inspector instead of getting them in an awake/start method.
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.
you also need GetComponentsInChildren
but also, that will literally get every single component assigned to all your children
my bad, i meant Component.GetComponentsInChildren
yup, children of children
and what about only children ?
if you need all the children of a particular gameobject, try the foreach loop i showed.
also, obstacles will need to be a list of GameObjects
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?
I'm not so sure if the foreach loop will only loop through direct children or not however. Documentation is not clear on that.
this path? https://learn.microsoft.com/en-us/dotnet/api/system.environment.specialfolder?view=net-7.0 use MyDocuments
Is that cross platform?
are you building for consoles?
Windows, Mac, iOS, and Android
Ik it works for windows and mac, found an answer saying it works for android, not sure about iOS.
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?
on windows for example it returns the Documents folder. So you should create a directory in that, not write files directly there. But again, not sure how it works for mobile devices.
what is the obstacle to using persistentDataPath?
is a specific platform not usable?
It seems I can put files in there, but I can't copy files out?
no, that's dataPath
misunderstood docs lol
on what platform?
Windows
AppData/LocalLow
why can't you read files?
exactly, I don't think windows likes you touching things in there
what?
but that's the default location
not true
It won't let me go nuts lol
what happens when you try?
then what problem are you having?
Unauthorized access
sounds like you've done something very weird to your folder permissions
are you using unity on something like a school or work computer?
Nope
show us the error you are seeing.
unauthorized access can also be thrown if you're trying to read/write from a directory and not a file
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.
and is TV a file or an entire directory?
that seems like a directory path, not a file path.
TV is a directory
then yea you can't read or write to a directory
iterate over the files in it and copy them individually
you need to create a file in the directory and read/write from there
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
!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.
trying to make shooting code for tank game, line 54 "tankColliders" error saying about Collider2D not def.
a powerful website for storing and sharing text and code snippets. completely free and open source.
what's the exact error?
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'
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.
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.
original code had "[]" in line 12 after Collider2D
yes, that makes it an array
but it generated error in line 25
by deleting it i got rid of the line 25 error and kept going
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.
ohh, so like ignore that part of the code?
idk what you're trying to do but
tankColliders = GetComponentsInParent<Collider2D>();
private Collider2D[] tankColliders;
yes, that was the original script but it made an error
on that exact 2 lines
what i sent was the fix to that error
tankColliders was not able to iterated, its not collection so you needed []
Assets\scripts\Shooting.cs(25,25): error CS0029: Cannot implicitly convert type 'UnityEngine.Collider2D' to 'UnityEngine.Collider2D[]'
it does this
I get it
by deleting the array it fixes
oh
and suddenly everything works
thanks i guess @rigid island @shell scarab
if something breaks i will try the layers method
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
Help with State Machines - Need to Pass Around Mutable Lists of States
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?
Would be better if you ask in #archived-networking or the ngo server.
Your client shouldnt be directly spawning network objects, at least in ngo it's not allowed
By spawning I really mean activating the pooled object
I'll ask there
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
well if its printing 0 that suggest that forceCount was at 0
And forceCount is 0. And subtracted by 1 so it meets the condition.
What is the difference between Forces.Count and forceCount? Curious how the latter is set
Edit: ah, in start
you have two different values, yes
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
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
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
yes but forceCount was 0
then you subtract one making it negative one
so zero is greater then negative one
forceCount is equal to the list.Count, which would be 1, not 0
then it subtracts 1, which is 0, then checks if above that
That is all what you think is happening. Not what is happening
Are you positive it's 1, because your print says otherwise
because that gets the current count, not the count during the Start method
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
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
Maybe forceCount was equal to list.Count (started as empty) but now, the list is updated.
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)
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?
Sounds like you want command line arguments. I'm pretty sure you just use System.Environment.GetCommandLineArgs();
yeah you can still pass it args like a regular application
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
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
@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
you could also divide it bu 60 then modulo by 60 and combine that
that or a TimeSpan.FromSeconds(clip.length) then you can ask that for the number of minutes and seconds to format a string.
would have to test, in this case would jsut from seconds then ${x.Minutes}m{x.Seconds}s
Where?
Can someone give me a movement script
That's not how this Discord works.
Then where can I go too get one
now you're both cross-posting and asking people to write your code for you.
Great, so start !learning
๐งโ๐ซ 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/
Thank you
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
How do you go about accessing your controllers after loading a different scene?
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
A callback as in I was about to ask you that lolprivate void OnSceneLoaded()?
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
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?
what are you trying to do? Client side prediction / rollback?
Yea, Ive gotten something sorta working for players but for non player controlled enemies Im struggling to wrap my head around it
Netcode has a system for client prediction:
https://docs.unity3d.com/Packages/com.unity.netcode@1.0/manual/prediction.html#prediction
oh shit that's the entities package haha
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?
yes
one is for GameObjects
one is for ECS
https://docs-multiplayer.unity3d.com/netcode/current/learn/dealing-with-latency/#client-side-prediction there's this
Tricks and patterns to hide latency, what's acceptable to manage client side with client authority before sending it to the server, prediction, server rewind, action anticipation, etc.
Sorry, what is ECS?
If you are asking that question you're definitely not using it.
https://unity.com/ecs
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
Why do you want to?
Basically always do it from the start. I converted once and... i'm still doing so
Just wanted to use netcode for entities for the client side prediction I suppose
Looks like client prediction is "in progress" for Netcode for GameObjects:
https://portal.productboard.com/36ukwpc4kysiqwfanhjdglcd/c/2339-scalable-netcode?utm_medium=social&utm_source=portal_share
Yea its been on the roadmap for a while
Yea I tried PUN first but I switched to NGO since that was the unitys implementation
PUN is not Fusion
Oh
PUN is a much older much shittier framework
I see
(both are products of the company called Photon)
So is there no solution to this besides switching to ECS or using another netcode implementation that already has CSP?
third solution is implement your own
Yea thats what Ive been trying to do
yeah sorry I sidetracked you because I didn't realize they didn't have an implementation yet
No worries!
These all look like fun rabbit holes to look into in the future
Especially ECS
Just wondering how to go about this still
I don't mean to steer you away. I love ecs, it is just missing a lot. One of the biggest things is that you can't use animations without big workarounds. Almost no normal unity component works out of the box really. But if you have an extra year to develop, go for it! Plus it only just got to 1.0 in may
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?
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.
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.
I think that has to do with rendering the object's inspector? What Happens if you don't have that object selected?
Don't currently have any object selected. Inspector is blank. Error persists.
I should clarify that this is happening with the 2D URP.
It there a way to have custom skins on characters like Additional clothing to a model without inserting such object into the model itself?
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
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));
Not really a coding question, but you can rig another model body part(for example torso) with different clothing and add it to the character prefab.
Unchecked is used as a scope:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/checked-and-unchecked
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.
yea i mean that's what I'm doing, only unchecking the conversion
I thought it was defined, that it will wrap around to the minimum (in this case) because the bits roll over to all 0s
No to a minimum, it depends on how much it overflows afaik. That's why you should avoid using it at all. Use a try catch instead.
The error is not caused by parsing but by assigning most likely.
Or both. But you're not wrapping the assignment in unchecked.
There is no guarantee that it has the same behavior every time. It might depend on the compiler and environment. That's why it's an undefined behavior.
For example, if you build IL2cpp build there's no guarantee that an overflow would work the same way.
hmm.
Been trying but nothing happened
not so much guides on how to do them as well
Should be plenty of tutorials on that.
Here's one for example:
https://youtu.be/nSmEirb8JGM?si=MTd13KY_0H1L5RpY
tested and its doesn't work as intended
the model have Weight paint and should be flexible
I believe overflow behavior is defined btw:
now it just disappeared
They cover that in the video.
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.
ok but the model is stiff and does not follow the character
i assumed it would wrap around to 0 then continue onwards like it seems to be defined to do? And, how could it be called erroneous if it's defined? but I guess it's only for actual operations and not casting.
it even says right thre that it wraps around from the maximum value to the minimum value
and made the source object disappeared
Okay, then I misunderstood you previously. I though you expected it to reset to 0 regardless of the overflow.
It's erroneous, because it goes beyond the defined value range. Ideally you shouldn't even get to that situation.
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.
It's not fine. Even more so, if it's user input.
What if they input some other character that is not parsable? You want to handle that as well.
yea want to see my regex code?
i believe it definitely is fine
Well, suit yourself then. If this kind of code was in a project I'm working it I would tell them to rewrite it.
why??
Is it a skinned mesh renderer?
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.
Yup
Tested on blender using the same model imported via fbx
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.
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
Move to #๐ปโunity-talk and share more details. This is not a coding question.
which can leave me with really big numbers. I want to reduce those numbers into a uint or a ulong. It doesn't matter how, just that it's the same each time.
sorry, I just really don't see where the problem is
That's not the issue. The issue is that the player might thing that all characters are fine and might think that they are part of the seed. You need to provide some kind of feedback to the user.
yea, by not allowing % for example be put in?
I want to allow letters and just turn them into numbers.
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.
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
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
Share the whole script or explain what line is line 51.
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
Ok, then character is null.
I'll check that and see if I can fix it from there thanks
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.
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 
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
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?
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
Hmm depends I guess, you can use define constraints or platform checkbox to ignore/not include assembly.. but there might be side effects if your assets are using it
Thanks, I'll mess around with them!
Because nothing was added to it probably.๐คทโโ๏ธ
I add Transforms in the Start() method
Does the start run?
Yes
Does the loop run?
Yes
It prints in The start The correct count
But somehow in The other void The count is 0
Then you either have another object where nothing is added to the list, or you clear the list somewhere else.
Is it normal for onClick event to not be visible in the inspector at runtime if added through code?
That can't possibly be the only code. You call that method from somewhere else, so...
Yes
Yeah i call the method from the other file but only this one has the access to obstacles list
Are you sure about that? Make the list private and test.
Iโm guessing theyโre referencing prefab ๐
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.
Yeah from the other script I meant
Can I ask for help here?
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.
If its code related yes, just ask instead of asking to ask
Ye, I prolly should have
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.
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?
base.Start calls direct parentโs Start if overridden
wierd, maybe something else is happening
Make sure you are using virtual/override Start
That worked thx
maybe you are looking for some of the public functions here
https://docs.unity3d.com/ScriptReference/Events.UnityEvent.html
although i dont really understand what the issue is with your code
Fixed the issue, I was adding a listener inside another listener which caused it to stack up.
It is
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?
are you using Action? or any kind of subscriber notification functionality?
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
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
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
sounds like you need an animation queuing system of some kind
so they're overriding each others animations?
Does my Player Controller call the UI to pop up or should there be another component on top of the Player Controller that disables all Player Input and manages popping up the UI?
Exactly
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
So is your inputs being served directly from player controller?
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;
....
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?
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
I'm thinking about a game manager that subscribes to all Events from InputReader (SetGameplay, SetUI...) and Game Manager sends a signal to PlayerController to ignore all Inputs
I do want to comment that the tree you have for the player controller is really good though
yeah sounds about right
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 ๐
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
Kinda how it's done (event sets a variable true, check begins in KCC, if check is true, FSM switches to climbing state, which triggers a camera shake and position sweep)
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.
Can I have the source?
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?
does your fsm have transitions abstracted?
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
well you can write everything in a single static class using goto instead of methods
Find it quite hard to write thos animations, so I thought maybe there's an easier way that saves me time and is less complex than writing my own XYZ Curves
then refactor to use methods
You could also just replace it with an animation with root animation? But you chose to do lerp
then refactor to use classes
Yeah well thats where wisdom from experience comes in
and so on, or you can simply select a good architecture from the start
perhaps you could do a spline traversal of some sort? Or root animation movement?
Yes, but if you're inexperienced in any aspect you could easily fall into overengineering something
just to pursue the 'better' system
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();
}
...
}
thats an imperative approach that is not completely an fsm
Don't know much about root animation, some guys told me to better keep movement and animations separated so I did that
Thought this is an Hierarchical Finite State Machine?
hierarchical just implies nesting, afaik, it doesnt specify what method is used for state change
Every method has its application, i.e you could do a root motion ladder climb to exit from one level to enter another.
Depends on your situation
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
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());
this is so verbose im failing to parse
i guess
this is an example i keep bringing up
Ouh, Behavior Trees
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
Boy that escalated quickly ๐
i wont bring its api because its fubar, but in general its a good example
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
if i seen some i wont remember which ones
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...
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
walking and shooting? sounds like you need animation layers or masks
Yeah heard about GOAP before, don't know if I should refactor my huge HFSM though
Guess I have to learn what those are first ๐
For now I just import some mixamo animations and play them in my Root-States with some Blending for moving left/right/front/back
yeah, animation is a whole different area
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
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?
store initial mouse click, each frame you get delta from it
adjust size based on that delta
and delta is currMousePos - prevMousePos ?
no, initial vs current will give you distance from start of drag
I watch this guy:
https://www.youtube.com/watch?v=_J8RPIaO2Lc&t=174s
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...
you need to keep the initial position as a point of reference
goes in depth with the functionality for everything without being a bore
but how do I know where mouse moves then?
or rather, the initial offset
where A initial offset, orange is after mouse move, red is the total vector used to adjust size
I see, but how do I find that red vector?
it's not the same as moving a panel
current - initial
current what?
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;
mouse position?
current offset
which is mouse position + initial offset
(current position + initial offset ) - (initial click + initial offset)
Vector2 offset = new Vector2(.1f, 0f);
_rect.sizeDelta = _rect.sizeDelta + offset;
_rect.anchoredPosition = _rect.anchoredPosition + offset / 2f;
whats the error?
that you cant ref in that scope?
how do I convert mouse position to this vector?
Cannot initialize a by-reference variable with a value, which doesn't make sense because both returns are refs
try decomposing that whole ternary into an if block
it will probably explain why it doesnt work
oh, probably this
_rect.InverseTransformPoint(Camera.main.ScreenToWorldPoint(Input.mousePosition))
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.
is it wrong to make small velocity adjustments by modifying velocity directly, if i also want the thing to work with AddForce() ?
It depends if your changes are additive or if they're overwriting completely
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...
theyre modifying local Y axis to make the thing more even towards the ground
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
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!
Ideally, each block will perfectly fit the allocated space it is in. In other words, each block most fill a X meters x X meters space. You can have variation depending on what is around the block.
If you do that, it is trivial to "snap" a block. Simply set its position to the closest position.
The simplest approach is using empty GameObjects to indicate the attachment points/orientations
assuming they're not just at regular grid intervals..
why after watching testing 10 ads, the PC starts to froze?
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
I was considering doing this but having to do it for all prefabs sounds like a decent bit of work. I am kinda trying to approach this to mimmize the amount of time I spend in future adding new content
how many "blocks" or whatever do you expect to have?
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
Using cube will make everything way easier and a lot less buggy.
anyway if not done manually, you'd have to establish some rules about how it works
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
It is not really the "best business" practice. In fact, I think it is a terrible business practice for small budget game.
And, people can still mod your game same if you do nothing.
why after watching 10 testing ads, the PC starts to froze?
We do not know stop. Stop spamming
I just want an answer...
Nobody knows what is your issue.
at least do u know how to switch from that 10 seconds unity ads videos, to an actual ad from a game?
No.
Ask in appropriate channel. This is the code channel.
Also, there is probably a forum for that.
And a documentation for sure.
is here a unity ads channel?
There is a #archived-unity-gaming-services
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
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
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) ?
is default (0,0,0)?
but yeah im pretty sure
what is this?
sounds like... an interface