#archived-code-general
1 messages · Page 315 of 1
Same
sahi hai bhai
What age r u? If i may ask
24
Yeah thanks 🙂
Being indian myself, Its always the indian guy who helps me lmao
When it comes to studies, gamedev haha
Anyone succesfully using a one source of truth type state management system ? Redux.NET seems pretty good but im not sure about unity compatibility. I wish Pinia could be ported to C#.
I've written my own reactivity system inspired by Vue's and used it in my Unity project. A primitive reactivity system is pretty simple to write, especially if you are willing to make some tradeoffs like not doing automatic dependency tracking, that basically reduces the whole thing to less than 100 LoC.
Was thinking doing the same but what I cant wrap my head around pre planning is the subscription (watch for change) aspect, C# isnt my strongest language.
There's not much C# specific about it. The idea is very simple:
- A signal keeps track of all the effects that uses it.
- When you do something with a signal (eg
watch), add the effect to the signal. - When signal changes, run all the effects.
I think I get it ish. Off to trial and error land it is. Because the existing libraries seem all to convoluted for what they are supposed to do.
@swift falcon https://www.youtube.com/@Brackeys watch this guy
Learn how to make video games!
Top-quality game development tutorials on everything from Unity, Godot and programming to game design. If you want to become a developer this channel will help guide you through it!
Join us on Discord: https://discord.gg/brackeys
► All content by Brackeys is 100% free. We believe that education should be availab...
Hi, this is a coding channel, please use #💻┃unity-talk for these questions
Hey! I have
-float angle in degrees(can be easily changed to radiants)
-origin vector2 point(game is 2d)
-float distance /magnitude
And i want to generate Vector2 with that angle and distance from origin,
I know how to do this in math like with explinations and calculations, but not sure how to approach it in unity components lol
like ofc i can do the long way but Vector2. has so many methods and stuff so i think there should be some easy way
nvm found it online lol
Is there an easy way of checking if the transforms parent has a parent with a certain tag?
The whole parent of parent and child of child stuff is a little confusing to me
var newPoint = origin + Quaternion.Euler(0, 0, angle) * Vector2.up * distance
Would be a possiblity
transform.parent.transform.parent.tag
Do I just add an extra transform.parent for every parent that I want to go up?
probably, but not a way I'd code it all. I'd make a specific field for that reference and make sense of what this greater parent is
Oh interesting, I would assume that I can do the same with transform.child?
sure, but if you can do it at editor time, just bind those references on the editor too
If you explain what you are trying to achieve we can maybe help you finding an alternative solution
I have added a run animation to my character but when I'm not running the running animation is still happening. how do I make it so when I'm running (pressing LShift & W) the run animation plays and when I stop running the animation also stops.
transform.root if you want the topmost
How are you applying this animation?
Ah this is perfect, thank you
wdym?
Im gonna have to write this down 👀
Do you have an animation graph?
im still new to this all I did was follow a youtube tutorial which is this: https://www.youtube.com/watch?v=9H0aJhKSlEQ&ab_channel=syntystudios
Animate a character with Mixamo
Check #SyntyStudios for more videos
Subscribe to Synty Studios on YouTube - http://bit.ly/2YPlWRp
Like Synty Studios on Facebook - https://www.facebook.com/syntystudios/
Check out all the different content available on the Synty Store - https://syntystore.com
Files required: https://www.dropbox.com/s/lyc53bvsohi...
https://img.sidia.net/ZEyI5/xuQagIdi75.mp4/raw you should have a setup similar to this
Whenever you are running you set the "running" bool on the animator to true and it transitions to the running animation, when you stop, set it to false and it transitions back to idle
when i run EvaluateTurns turns.IndexOf(turnGrahic.turn)Returns -1 why is this (MakeNewturn gets called about 6 times and then EvaluateTurns right after so nothing else should be messing with this)
Please dont post a screenshot to your code, use: !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
What is best practice for using Floats?
what
can you share the definition of Turn and where turns get added to the turns list?
Your turns does not neccessarily contain the same stuff as turnObjects
If I can represent a float as an Int what's the point of using a float. Essentially is what Im asking.
you cant, not in most cases. Not sure if I understand
public class Turn
{
public Turn(BattleCreature creature, bool ally)
{
this.creature = creature;
actionValue = 10000 / creature.instance.stats.speed;
this.isAlly = ally;
}
public BattleCreature creature;
public float actionValue;
public bool isAlly;
}```
Ex. 15%, instead of 0.15f I just do int 15.
Oh and instead of creating a new Turn to add to the list, just add newturn, might actually fix your problem already 😄
OH
That's pretty vague. Is there anything in particular that made you decide to learn more about best practices with floats?
can you elaboate? What do you mean?
than you i can believe i over looked that
how do you represent 1.5f as an int
you can find an integer that looks kind of like any given float
lol
If anything, use approximations and ranges when comparing values
that's not meaningful, though
123 kind of looks like 1.23f, but so does the string "1.23"
use floats when you need to represent a non-integral value
My main issue I had posted about was yesterday. I had created a List<StatType,float>
When combining 0.15f + -0.15f I got 5.9.......... something something.
I was wondering if I should just do away with the Floats and replace them as Ints instead.
Likely 5.9 x 10E-10 or something - practically zero.
floats are inherently a little bit inaccurate, if you need exact precision you can use int types but for most physics and game logic it doesn't matter
I really just wanted to know if I should continue using floats or swap to int's. And in the future if I run into code that I think needs to be a decimal, should I convert to int to avoid these problems.
never expect exact equality when comparing the results of float operations, use Mathf.Approximately or whatever
well if you need floats you use floats and if you dont you use int
To go into more detail. It was an accuracy up being applied to a character. Then it got hit with accuracy down. It SHOULD HAVE been 0.
no reason to use a float if int can do the job
Ahhh ok see, this is kinda the answer I was looking for. Something to remedy my issue.
things like RPG stats are often better as ints, like currency, you actually do want the exact precision
Hi, I have an event to which I subscribe 2 methods (line 15 of ChillState and line 39 of InputManager), but one method (the one in ChillState) isn't being called when the event is invoked. I used Delegate.GetInvocationList to check that it's actually subscribed and it is. Any thoughts why this might be?
https://hastebin.com/share/gayudirose.csharp
https://hastebin.com/share/gimemihoju.csharp
I also used to have Unit Level up bonus's which were in the same boat, it was a aList<StatType,float> . Ex. Strength 2.6 * base each level up. But that can easily be remedied with Mathf.RoundToInt
@thick terrace Thanks for the talk.
Any response for this earlier question?
I don't see where you invoke the event
Cast is subscribed to OnStartTouch (InputManager Line 103), which is invoked in TouchPressed() (Line 121), which is subscribed to touchPressAction.started (Line 36), which is invoked when you tap the screen
it's a bit convoluted ik
That's not how delegates work
If you do that it's not going to pick up updates to Cast
Cast gets reassigned when you subscribe something new to it
Oh right yeah I remember now I had the same problem a while ago. That's why I made that AddToUncast() Method on line 139
Oh wait that's not quite the same
But thanks I see your point
Hey, i was wondering if it is possible to make a variable in an interface optional. i would like the string to be optional
because at the moment i get this error "Assets\Dev\InteractableObject.cs(2,50): error CS0535: 'InteractableObject' does not implement interface member 'IInteractable.Tooltip'"
that would defeat the point of having interface though
also thats a property , interfaces cannot have member variables
No because the point of the interface is to guarantee that the property exists
i couldnt think of the correct term its 2 am rn lol
okay thanks anyway :)
Assuming you're using Unity 2021.2 or newer, you can use default interface implementations:
public interface IInteractable
{
public void Interact();
public string Tooltip
{
get => string.Empty;
set { // do nothing }
}
}
that works, thank you :)
is there a way to check if a collider has collided with any raycast without using hitInfo.
why
are you using ECS or gameobjects?
also colliders dont hit rays, raycast hits colliders 😛
to see if i can find a shortcut for something i am doing
ye i mean that sorry wrong wording
how's anything else gonna be shorter than the Raycast hitinfo ?
maybe explain what you're doing , might be able to offer better alternative
ECS or gameobjects, @surreal cloak ?
For gameobjects, this and its other similar methods may help: https://docs.unity3d.com/ScriptReference/Physics.CheckBox.html
For entities (ECS), here's similar: https://docs.unity3d.com/Packages/com.unity.physics@1.2/api/Unity.Physics.CollisionWorld.html#methods
you can also use RaycastAll to return a list of all objects hit: https://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html
that's gameobjects, btw.
Which is what?
I'm not sure how this relates to what they want to avoid lol
without using HitInfo I'm assuming is raycasthit, I dunno. just wanted to feed info.
I mean you could just, not use the parameter in Raycast though?
It would be useful if they explained their usecase lol
RaycastAll gives RaycastHits too though
ya lol also this
guess we'll never know what
for something i am doing
means :p
the CheckBox, CheckSpehere, etc returns just a bool. the *casts methods use raycasthit, and has certain flexibility.
Those are just shortcuts for Overlap methods which are not casts
what other ways can I save data?
https://hastebin.com/share/kunebukeku.csharp hi, i am making a script for the player to throw a katana but I have a coroutine that returns the sword to the player that for some reason runs after the sword returns for a little bit (sometimes). this makes it (I think) so after a few consecutive throws, the katana will throw for like half a second and immediately return, not going its full length. (btw this happens when the player hits the enemy not just throwing it into the open sky.) tried making it so when you catch the katana and even when it is in the distance to catch to stop both theThing and the FollowHand coroutine but the issue persists
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
lots of ways, Binary serialization, JSON, YAML, XML, CSV to name but a few
Say I want to serialize a class I have no control over, like something from a Unity package
Is there a way to do it, or is it just not possible?
Just a suggestion is to let the coroutine itself break via flags instead of having to stop the coroutine may make things a bit more logically confined.
what are flags
IEnumerator SpinSwordAsThrown()
{
while (!returningSword)
{
transform.Rotate(thrownSpinSpeed, 0, 0);
yield return null;
}
}
What you're doing here is a good example
ah
FollowHand() calls StopCoroutine on itself which I'm not sure how that behaves
Your variables inside of that coroutine too may not being reset as they are member variables, so make sure stuff like the returning force is changed back to defaults when making a new coroutine.
I put it in the catch method
Ah, I see. My best two guesses would be the values arent resetting, or that you have multiple coroutines running that are changing the values which you may not be aware of.
yeah that makes sense
which is why vs debugger is great for debugging coroutines
how do i debug coroutines tho theres no way to get its status other than bools which isn't really helpoing in my case
If you're doing it by logs then putting them directly in the coroutine yourself
unfortunately not easy to debug per instance though (well, you can identify them inside the coroutine scope, but iterating over a list of coroutines does not yield anything too useful)
oh
i do notice after debugging that the variables are being printed multiple times (i have collapse on) even if its the same value
Could anyone tell me the most straightfoward way to ensure text (tmp) only shows from one direction, like a real life notecard, even if the material is transparent?
is that how it works now from one direction?
If I flip the card, I can see the (backwards) text on the reverse side. I don't want that
I gues this is 3D TMP so parent it to a Quad
ohhh the 3D one
I may be misunderstanding, but parenting it with a quad didn't fix it
and yeah it's 3d
i did. Did you flip the Quad 180?
yeah.. the quad only renders from one side, but the text still shows through
You could just always use a World canvas if you wont have many of this 😛
It's a VR app where user can grab and manipulate the notecards, so it's a little unorthodox I guess. I'm surprised it isn't more straightforward to solve this lol
Worldcanvas would make more sense to me here
but yeah thought there would be an option on the 3D mesh extra settings to render one sided but alas none I found
I'm actually using the asset Nova for my UI, if you're familiar with it. It's all world space
It integrates TextMeshPro
Unity's UI just looks like puke to me so I preferred to use Nova. Alas it leads to situations like this tho, hah
Oh I'm not familiar with it, are you able to use the TextMeshPro UI version of text? I would use that then
Even with that it doesn't seem to make a difference.
Oh well, it's not a total gamebreaker for me, but I'm sure I'll run into this issue again someday
works for me
are you using sorting layers or anything
yeah the problem is the notecard is a semi-transparent 3d object that needs to be consisent on both sides, i just want the backside to not show the text. might require a specific shader or sth
Ohh I see, if the quad is like 'inside' the 3d object it will still work I guess
What is a good way to have a list of classes that derive from a base class, but which hold unique data types, and then retrieve them?
Like, say, PositionData derives from BaseData, and AnimationData also derives from it.
PositionData holds a Transform, and AnimationData holds an AnimationClip.
I then want a list of BaseData, which contains instances of both PositionData and AnimationData.
Then I have a Function, "PlayAnimation", which takes in a BaseData as a parameter, but I want it to only ATTEMPT to retrieve an AnimationClip from it, so if it's passed an invalid BaseData which doesn't contain that variable, it doesn't throw an error.
Does any of this make sense? Apologies if I'm not explaining it well.
why do you need it specifically to work that way? why not write a PlayAnimation method that only takes AnimationData if that's all it can use?
I'm working on a modular statemachine for a turn-based RPG, so I need to be able to build complex custom "actions" that the player can perform.
at what point would you pass a non-AnimationData object to PlayAnimation though? i'm wondering why you'd need to avoid something like if (data is AnimationData animationData) PlayAnimation(animationData)
PlayAnimation should be able to play something like a lerp as well as an animation clip ?
Look, this should explain it better. Here's a snippet of my design document, where I'm trying to piece together the architecture of a state machine for playing character actions.
has anyone used urp render objects and stencil shaders
i need helpp
Basically, I want an action to be able to;
Bring up a UI unique to it when selected
Perform a unique action with that UI input
Perform multiple actions if need be, in any order
Provide Control, Modularity, and Complexity for designing actions, playing them out, and modifying them in editor or runtime.
So I'm designing it to be polymorphic, and am working on what sort of design elements suit that.
This has nothing to do with what you were talking about earlier.
maybe it's a bad example then? PlayAnimation is a method which seems very specifically about animation, so i don't see why you'd want to allow parameters of other types
It does, it's relevant to what I'm working on right now, which is if I can use an array of BaseData in order to hold a variety of data types, pass them to a script that takes in a BaseData, but then ensures that contains the correct variables before using it to perform a function
Also, those are actions not state. You might want to correctly divide between the state of the character and its "behavior".
They're part of the state machine, my plan is for them to run coroutines.
So EvokeUI waits for UI input, then progresses to the next state, MoveToTarget starts a coroutine that waits for the character to reach a given point, then progresses the state machine
Ect, ect
https://hastebin.com/share/ilepizawuc.csharp how come when the katana hits an enemy it comes back fine but if it doesnt hit an enemy it just flies off into the distance
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
There is so many way to approach this issue. Not sure you should settle on one particular implementation at this point. You could by example, query the parameters, or pass them at the creation.
They are not the same as a "Character State" such as Move, Attack, Dodge, etc. which can quickly become confusing. Instead, I believe you will be better in trying something like a Action Queue, a behavior tree or any other AI pattern. This way, your player and your enemies can have the same underlaying capacities while having different behavior.
Also, you might want to redefine your Evoke function. Using Coroutine is a bad idea as you are going to have potentially multiple "thread" running at unknown time. You should look into doing a Start, End, Update. (You can also have potentially others such as Interrupt, PhysicsCollision, etc.)
I've read that using coroutines for Turn Based Combat is common, though?
Coroutines sound like a nightmare for turn based combat. Coroutines are really just lightweight/poor man's state machines. A full fledged state machine would be better
No, it is not. It is possible to use them, but definitely a bad idea. You have less control over them. You should favor using your own Update logic.
public abstract class EntityConditionsBool : ScriptableObject
{
public abstract bool EvaluateCondition(IEntity target);
}
public class UnderActiveEffect : EntityConditionsBool
{
[field: SerializeField] private ActiveEffectSO ActiveEffectSO;
public override bool EvaluateCondition(IEntity target)
{
foreach (ActiveEffectBundle activeEffectBundle in target.ActiveEffectBundles)
{
if (activeEffectBundle.ActiveEffectSO == ActiveEffectSO)
{
return true;
}
}
return false;
}
}
So I was thinking of a class like this for conditions for characters. Problem is I'm not too sure of the best way to structure it for return types, as well as being able to work with it on the editor.
I dislike the SO Idea as that's a lot of asset bloat so I'mma just use serialize references
Another class would be something like this
public abstract class EntityConditionsInt : ScriptableObject
{
public abstract int EvaluateCondition(IEntity target);
}
public class GetNumActiveEffectStacks : EntityConditionsInt
{
[field: SerializeField] private ActiveEffectSO ActiveEffectSO;
public override int EvaluateCondition(IEntity target)
{
foreach (ActiveEffectBundle activeEffectBundle in target.ActiveEffectBundles)
{
if (activeEffectBundle.ActiveEffectSO == ActiveEffectSO)
{
return activeEffectBundle.ActiveEffectApplications.Count;
}
}
return 0;
}
}```
So it's like a class for each type of return value that I want? Ye or nah? I feel like the serialization is what's holding me back here
I usually implement "Serialize Condition" as "SerializeReference". Not sure what you are referencing for your issues ?
It seem to me that you are trying to serialized to much "code" and instead you should simply code it. Do not overthinking it, just make a class for every scenario. If you really, really wants to do that, you should instead create a Graph Editor such as what you can see with VisualScripting. It is 100% better to edit "serialize code" in this format.
Coding it directly would be a solution, but I was looking for like absolute modular code that I could just wrap these in with other classes
Probably a bunch of other classes where I do need to know if they have a specific amount of effect stacks, if they are under % hp, stuff like that
By doing so you are effectively doing what we call overdesigning. The code is going to be harder to maintain, less performant and strangely enough you will most likely find yourself struggle with flexibility.
Yeah, I can see that and it would probably just be easier to duplicate code if I need to
It is nice though a lot of my systems I can just move and replace without touching the underlying code because how component heavy it is
Obviously, it depends on how much you are going to use those condition and how specific they are.
Hi there, simple question, how can I get an angle of a direction vector:
_newDir = Handler_Gamehandler.Astro_UnitCircleVector3(transform.eulerAngles.y + (i * 45));
Instead of transform.eulerAngles.y I want to use something like PathfindingDirection.y but it is obviously, 0
Could I have some pointers for this problem?
Visual scripting does seem like a fine idea too, but it's one of those tools where I'd forget I was even making a game
Yeah, that is exactly what I'm saying with your current implementation as well.
If you make a FireBall, just code a FireBall class.
No need to make everything abstract and generic.
but generic projectile that has a chance to explode into smaller fireballs that have a chance to burn the enemy and make the enemy explode when they die is pretty cool too
swap out the fireballs for icebolts in a single SO ;)
I usually have projectile generic too. But I also keep the possibility to have non generic one.
It works well if your game is not that complicated. But when you start to have specific condition that only make sense in a specific context it start to being a hindrance more.
It's unfortunate, but larger reason it is this modular is because I'm bad at having stuff planned out in design
Even worst idea to make modular.
one day I want fireball, the next day I want fireball storm
Modular means that you are adding limitation and you make a lot of assumption.
From the little experience I have, I can guarantee you that the worst you are at planning the worst modular architecture are. It is always 100% easier to replace code of a single whole class then replace code of 5 smaller class and adding context specific module.
How can I make an if statement using colors and/or arrays?
same way you use it other ways?
Yeah, just check the color and make sure it's equal
How do I do that?
==
Here's the code: https://pastecode.io/s/ybih333z
if (colors[i] == color) for Arrays
that OnTriggerEnter2D 😵💫
What's [i]?
Assuming you use a basic for loop... for (int i = 0; i < 10; i++)
Hey Navarone, do you have an answer to this question?
what are you trying to do with it? I'm kinda horrid at trig math
a vector is a direction pretty much no ?
Yeah, but I'd like to add unto it:
{
_newDir = Handler_Gamehandler.Astro_UnitCircleVector3(angle + ((i * dirA) * 45));
//If not detecting a wall, go ahead
if (!Physics.Raycast(transform.position, _newDir, distWall))
{
break;
}
}```
Here is the full context: I'm trying to test directions to see if a certain direction is open for the npc to move towards too
I've done some more research on action queues, and now I'm wondering if I shouldn't use a Queue for most of my statemachine. Are queues good for that? From what I've seen, the way Dequeue returns what it removed and works via FIFO seems to be perfect for switching from one state to another, while having the list of states themselves be modular.
are you not using navmesh or is this 2d?
ahh ok yeah trig math is not my forte
also might want to post Astro_UnitCircleVector3 for anyone who might know
{
float unitCir = degree * Mathf.Deg2Rad;
return new Vector3(Mathf.Cos(unitCir) * radius, 0, Mathf.Sin(unitCir) * radius);
}```
I'd do it with a Quaternion that describes one "direction increment" (360° / number of directions to check)
Then multiply it with your direction vector to rotate said direction vector
Quaternion rot = Quaternion.Euler(0, 360 / 6, 0);
Vector3 dir = transform.forward;
for (int i = 0; i < 7; i++)
{
dir *= rot;
// use 'dir' for raycast
}
Something roughly like this
Oh, I really don't want to use transform.forward
Oh yeah it is
helo, i hav been making a 2d game i wanted to ask if i could make a infinite random generation but i want to keep some stuff the same like the sky and the ground and iwant it so after the player leaves a part it disapears behiund him any tutorials u guys can recommend i cant find any
so infinite runner?
yep
lookup endless runner 2D , many tuts on it
generally involves keeping track of position and if it goes above threshold spawn pieces
I've reworked my design doc to implement a class based statemachine with its own update logic instead of coroutines. Does this look like a healthier structure to build off of? The Combat management goes through provided states, and uses them to modify other character's statemachines.
It already seem better, by instead of passing "StateData" I would either simply make a function PlayAnimation(AnimationClip) or GoTo(Vector3) and pass the information either in a specific state constructor or a initialize function.
I want to be able to have more complex StateData later on, though, like if I wanted to have an action that had the player shoot at multiple enemies, which would require data on multiple vectors.
I'll have to do some more research and think on how I might structure that.
In theory, I could have a single CombatState which just assigns a player a full list of their States to travel through and all information needed for all of them.
hey everyone, looking for a solution to finding the 4 corners of the screen on a world space canvas.
my world space canvas is much larger than what the camera can see but i want to find those corner coordinates of the screen corners on the canvas.
any tips?
new Action(MyParameters)
I tried it- Didn't work, gave me an error cause you cannot multiply quaternions by vector3
I'd like to round the angle to 45* anyway if possible
That would be 360 / 8 or just putting 45. Afterwards it depends on the initial direction vector and around which axis you need to rotate it
My example assumes a direction that is flat (no Y value) that needs to be rotated around Y
(it would make a circle when viewed from the top)
Use the stuff in the Debug class to visualize the resulting direction vectors
what's a good way to go about a database for data needed in game, say a list of weapons with their stats?
i've tried the scriptable object route and it works but is super annoying when you want to edit a lot of them at the same time
i feel like something with a table format would be easier, say CSV, would that be a decent idea?
for (int i = 0; i < 8; i++)
{
_newDir *= Quaternion.Euler(0, 45, 0);
Debug.DrawRay(transform.position, _newDir.eulerAngles, Color.magenta, 5);
if (!Physics.Raycast(transform.position, _newDir.eulerAngles, distWall))
{
break;
}
}```
Gives me:
I just need it around a circle which is why I requested the angle in the first place
What's dirA and why is it included in the rotation quaternion?
It's a simple -1 or 1
Also not sure why you made _newDir a Quaternion, it's supposed to be a Vector3 for it to work properly
Right, the operator only works on one side because of matrix multiplication rules
_newDir = quat * _newDir;
Let me try this
Alright, that does work
But I'd like to it to be rounded to the next 45*, the initial rotation
I think I got somethign but I'm not sure
public abstract class CombatState
{
protected ActionStateData stateData;
// Constructor to initialize CombatState with ActionStateData
public CombatState(ActionStateData data)
{
stateData = data;
}
// Virtual method to be overridden by derived classes
public abstract void Evoke(ActionStateManager actionStateManager);
}
So basically something like this, as a constructor, so when I have a CombatState, it requires the correct information by default?
The reason I want to round it the nearest 45* is so I can avoid things like this happening:
Okay, I think I'm confusing you guys, sorry, I mean I want to snap it to the nearest 45* angle
There's no way to successfully do a 'GetComponent' on a component you've disabled previously, right?
have you tried it?
yeah, it returns null. and google indicates it's not possible. wondering if there's some other workaround without having to keep references
getcomponent should still return a disabled component. are you sure you are calling it on the right object and that the component is disabled and not destroyed?
ok my bad, i read some google results wrong and it confused me. sorry
you said you tried it
Wording is ambiguous, we don't know if you're attempting a disabledComponent.GetComponent<T>() or a GetComponent<SomeDisabledComponentType>()
But shouldn't matter, both work
yeah it was returning null because i did something else wrong. i misread some google search results and thought the issue was getcomponent doesn't work on inactive components
GetComponent will find and return inactive components, and you can call GetComponent on a disabled component.
Disabling only prevents some Unity messages like Update and FixedUpdate from running, the other members are still fully accessible
Does unity have anything that lets me easily change a gameobjects layer through script?
ah nvm, seems like it is something as simple as adding a .layer at the end
which would be the reason for a function (in this case Die) to not be called unless the highlighted variable is set to public? Even though Im not trying to access it from any other script...
I noticed, however, a weird behaviour in Unity while working with this: When the variable health is public and I run the game, the function Die is still not called when the condition for it is met. When I quit and run the game a 2nd time, the function is called immediately without the condition being met...
I don't see any code in here that calls Die at all
on Update, if health <= 0 then Die
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and this is from other script
why would you do that in Update?
That makes little sense
just do it in TakeDamage
Anyway - Debug.Log is your friend
log what the health is
I would guess it's not less than or equal to 0
Just did it
health's value actually decreases, but for some reason there's no effect
Do you have multiple of these scripts?
Not with screenshots, folow this #archived-code-general message
Could you be looking at the wrong one?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicEnemyAI : MonoBehaviour
{
int health = 100;
EnemyCounterScript counter;
// Start is called before the first frame update
void Start()
{
counter = FindObjectOfType<EnemyCounterScript>();
}
// Update is called once per frame
void Update()
{
if(health <= 0)
{
Die();
}
}
void Die()
{
counter.enemies--;
Destroy(gameObject);
Debug.Log("Die is working");
}
public void TakeDamage(int dmg)
{
health -= dmg;
Debug.Log(health);
}
}
That's the enemyAI code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawnerControl : MonoBehaviour
{
[SerializeField] GameObject spawner;
[SerializeField] GameObject enemyPrefab;
[SerializeField] BasicEnemyAI enemyAI;
// Start is called before the first frame update
void Start()
{
Spawn();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown("p"))
{
KillEnemies();
}
}
void Spawn()
{
Instantiate(enemyPrefab, spawner.transform.position, Quaternion.identity);
}
void KillEnemies()
{
enemyAI.TakeDamage(100);
}
}
void Update()
{
Debug.Log($"My Health is {health}");
if(health <= 0)
{
Die();
}
}```
Do this
Where on earth are you getting the enemyAI reference from
given that the enemy seems to be getting spawned in Start
and you're ignoring the return value of Instantiate
the only possible conclusion is that you have referenced a prefab in the inspector
obviously you are then just doing damage to the prefab
not to the actual enemy in the scene
The reason this might start to "work" when you make it public is that you are then serializing the health variable
and so it's saving between play sessions in the editor
You need to actually reference the copy of the enemy that you spawn
Instantiate returns that reference for you.
I see
yeah, looks like I was referencing the wrong object, it works now
thanks btw
Highly recommend moving the health check from Update into TakeDamage next
actually, I have a huge mess in these codes... looks like I will have to fix a lot of mess
Yall, Im confused, in this script: https://hastebin.com/share/ozojexamup.java
the noMoreSeeConnector boolean becomes true after a set of conditions have been met. In the debug log, I can see that it does become true, but for some reason, the else if statement doesnt run. I have tested the else if statement without the boolean check and it works fine, so Im confused why adding the boolean check causes it to stop running, even if its conditions are met.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ah shit, I figured it out
that one was tricky though
How do I make a gameObject's sprite = another gameObject sprite in a randomizer. For context, I'm making a tetris game and want to make a tetromino be the same as the oppentents when it shows up.
What have you tried?
I tried using an if statement, but that didn't work.
Be less vague, show your work, explain the issue and errors.
"Didn't work" is always gonna be an unhelpful response.
And an if statement is going to of course be a part of any conditional logic, but of course not the actual way of changing the sprite.
This is still really wild, but yeah, formatted way better.
So which part of the code is the attempt on the sprite code?
I think line 33
It looks like this isn't your whole code, so maybe my line numbers aren't the same as yours
You should really share the whole thing in an actually halfway decent code site
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I recommend gdl.space most
You literally used the exact same paste site
And why did you say your formatted it again?
Because people kept saying I didn't format it when I did format it.
Ok, yeah, your previous code cut off the color array, so that was very confusing
Oh
It is mostly formatted now, but it ABSOLUTELY FUCKING WAS NOT before 😸
Lmfao
Ok
So I see you setting the color of the sprite renderer to a random index in your color array. What is wrong with that?
You want to change it to an actual sprite?
No, I was just using sprite as an example for my problem.
But the thing is, how do I make the oppentents color the same as the players?
Get a reference to the players ColorScript i guess? Grab the color from that.
I dunno the architecture, so I'm not sure
How do I do that? I don't understand what you're saying.
I am saying that I don't have enough information to provide an actual answer
To get references, you can do one of these methods
https://unity.huh.how/references
Referencing things is a very important and foundational thing to know how to do
Not sure if its better here or editor-tools
With how unity has the "New Script" contextmenu option that makes a default monobehaviour script, can I make and list my own template?
you can edit the default template . . .
Oh neat! would be cool to add a different one but for now that would work, mind leading a horse to water? 😄
any search for creating custom script templates in unity will do. i just found this right now . . .
https://www.youtube.com/watch?v=YpKJedxBxks&ab_channel=SunnyValleyStudio
new user to unity. i have a college project i’m working on which in the grand scheme of games is quite a basic task. I just need a 3d game with basic features like movement, enemy ai, inventory and a few other things which i’m sure is quite easy for most of you but i’m terrible and no matter how many youtube tutorials i try i always seem to fuck something up so if anyone is willing to guide a complete beginner through the learning process dm please. thanks
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Can someone explain to me why line 45 causes a NullReferenceException error despite me having the EventManager script execute before this script (through Script Execution Order)? It may be important to note that the EventManager script and this script (GermManager) are attached to the same empty GameObject. EventManager uses the Singleton pattern while GermManager does not. I'm willing to provide more details to anyone willing to help.
where do you assign EventManager.instance?
Also where do you assign EventManager.onEventConclusion?
Start() method of EventManager
That's your problem
it should be Awake
Start runs so much later than OnEnable and Awake
Doesn't fix it though. I've tried both, and modifying Script Execution Order.
Thanks, it's gone now. I didn't try both (the Awake change and the Script Execution Order) simultaneously before.
whats typically used for rotating a character towards a target position with a speed value like rotateSharpness? Quaternion.Slerp? Quaternion.Lerp? RotateTowards?
If you want to rotate it at a certain speed, rotatetowards because the last paramter takes in the max angles it can change.
Im working on a dynamic weather system for my game, starting with rain, though im not sure the best way to handle transitioning surfaces from "dry" to "wet", im using a shader with similar properties to the default lit shader with a "wet value" slider (and other weather-specific params) but this means id have to replace maybe 70% of the materials on most maps and slowly blend between them - what might be a good way to handle this change? Should I make a very large array and add every object in my maps that I want to change the material of? Does it make more sense to put this shader on all surfaces at a "wet value" of 0 even during times where its not going to rain? Or is there maybe a better way to handle this? The idea is for example, is a concrete sidewalk on a sunny day, then it starts raining and slowly that concrete becomes wet/damp/porous, but there are a lot of concrete sidewalks and other surfaces in my maps that should be affected in a similar way
Slerp or RotateTowards, depending on your use case
thanks
ah i see i think ill use rotatetowards then
what circumstances does colliderField.bounds.size.y return 0 when it's not 0? I think for prefabs it does for example. Any other times?
Whenever the object is deactivated
🙏
Or the collider is disabled
ok that might be it let me see.
can somebody recommend me a way to handle slopes in platformer correctly?
What does correct handling of slopes mean to you?
I would go one of two ways for this. Have a global wetness shader variable that all materials read from and is set from the weather system or if you use deferred rendering you could have a wetness pass on GBuffer that renders after the regular GBuffer
Yo guys! I'm trying to make my raycast ignore the colliders of my own player, but I don't want to use layer's as I'm making a multiplayer game, and would still like for the bullet to hit enemies using the same player prefab.
I tried so many things and this is what I have so far.
foreach (RaycastHit hit in hits)
{
if (hit.collider.transform.root.gameObject != transform.root.gameObject)
{
TrailRenderer trail = Instantiate(bulletTrail, bulletSpawnPoint.position, Quaternion.identity);
StartCoroutine(SpawnTrail(trail, hit));
break;
}
}```
It checks if the collider it hit is a collider of a child in the current gameObject's root parent.
However! When there is another player (spawned in with the same prefab, but still it's own root parent), the bullet also goes straight through him?
I have absolutely no idea anymore how I should make the raycast ignore ONLY the player who is shooting and I've tried sooo many things.
anyone have an idea what to do?
just because you are doing multiplayer doesn't mean you cannot use layers. just put only the local player on a separate layer
(assuming you are doing this check on the local player, that is)
Im thinking the "global wetness variable" would be a good idea, though id still need to set each part of the map that should use the shader somehow, unless its better to always have them applied to objects before loading the map, even when it wont rain?
Just use a normal raycast. Change the player's layer temporarily while you do it:
int oldLayer = playerObj.layer;
playerObj.layer = Physics.IgnoreRaycastLayer;
// do the raycast with a layer mask
playerObj.layer = oldLayer;```
Wow I can't believe I didn't realize that.
I guess I just assumed that the netcode would automatically update the layer for everyone else as well, but if I just do it locally of course it would work. Thanks!
I dont get your question. What do you mean by each part of the map?
Yeah I considered this, but since it's a minigun, the player would just constantly be on the IgnoreRaycastLayer 😅
I think this was part of the problem, thank you. I continue to struggle on 
I don't see how they would "constantly" need to be on anything
it would just be whenever you do a raycast
Anyway me personally I would go with screen space wetness like shown here https://github.com/alelievr/HDRP-Custom-Passes/tree/master/Assets/CustomPasses/Wetness
Oh I think I get it. Yes you would always have the wetness shader on the material and it will just read 0’s when it is not raining
That would be preferable that the state changes cause by swapping materials
I mean I guess... I'm not that experienced with game making so I just assumed that the player would be on the IgnoreRaycastLayer most of the time if shooting, and I wanted to prevent creating any bugs or issues for myself in the future
Unity is single threaded
it would not be possible for any other code to be doing anything between your lines of code
oh I never knew that! That's really good to know!
Ah I see, thanks for all the feedback! Out of curiosity, how does this "screen space wetness shader" work? Is there any resources that could explain the technical part behind it? What I dont understand is, if its screen space its not actually applied on specific objects in the scene, so how would it know how to turn things wet or dry? Is it based on camera distance or sampling the camera every frame and then applying "filters" above it before it gets rendered over the screen or something?
screen space shaders can still use things like depth and normal buffers
so they can still know how far away a surface is and what direction it's facing
Interesting, that sounds like a really cool technique
In deferred rendering there is this thing called the GBuffer that holds material information for all objects, objects first get rendered into that then light is calculated on the buffer. With the technique in question you would modify the normal and roughness values of the buffer after opaque rendering but before light calculations
If you search for screen space wetness, GBuffer wetness online you should find a plethora of resources
Awesome, ill look more into that, thanks again!
Im thinking about redesigning my object pooling system and could use some tips. i have a singleton pool manager that takes care of all object pools like VFX, bullets, etc. One annoying part is populating the data. I'm stuck either manually linking each prefab in the inspector or letting it create what it needs at runtime when it's first asked for an object, which I feel isnt great. The first time an object is grabbed, itll spawn a lot of them.
As I add more features like "projectiles dont hit the character that spawned it" I feel this system is becoming clunky. I could solve this but I dont want to go deeper into a solution if it isnt good from the start. Im thinking of each character having it's own pool, which would make the above case easier but also enemies on spawn and death will be creating/destroying a lot of objects.
Im not sure if i should remake this or just tough it out with a single pool, anyone have advice on this?
does FindObjectsByType work from an editor script? need to get all objects of type in the scene from my editor script it keeps returning none found, trying it on a monobehavior works fine which makes me think this won't work from editor scripts?
Hi, i've got a question, is their a way to have multiple Time scales in unity ? like being able to pause the game but still be able to move a free camera with a kind of deltaTime ? If possible is it a good practice to do so ?
This should work in the editor.
maintain your own timescales based on 1
what do you mean by this ?
there is only one timescale in unity, so you need to do your own
https://forum.unity.com/threads/how-to-create-multiple-timescales-to-different-rigidbodies.274168/
oh okay thanks
The 1 means unity timescale then you apply some multipliers on it to have your own timescales
this might sound weird, but is there a way to have a game that simulates at 60 fps but renders at higher framerates ?
Or maybe is there a way to sync all my scripts in a 60 fps loop
Does anyone use Unity 2023? If yes, have you encountered a bug where when you change a field in the inspector, it resets back after deselect-reselect?
I cant invoke from within a scriptable object?
FindObjectOfType<PlayerCharacter>().Invoke("PlaySound", 0.25f);
method works without invoke
No. If it was possible, you, perhaps, could've played all the games at 1k fps
You might want to adjust your frame rate by setting the Application.targetFrameRate integer.
Application.targetFrameRate = 60;
fixedupdate fires at rate of about 50fps and rendering and Update() can be higher
is there a way to speed up FixedUpdate ?
how should i post my code when i have multiple files?
Yes, by changing its frame rate in the settings
is it a good idea ?
i'm trying to make a fighting game and i'm trying to implement frame data that is synced at 60 fps
No, it's usually a bad idea.
You won't be able to set your frame rate to 60 fps if it's currently 40.
You will be able to set your frame rate to 60 fps if it's currently 80.
What is it supposed to mean?
is there a way for me to call a different functions 60 times per second and that is synchronised through all my scripts ?
like script A and B both have a function that they need to be called 60 times per second, at the same moment
make the loop in a class and have it invoke an event anything that needs it can subscribe to
Consider using a Coroutine, I would say
This loop should be made in a Coroutine.
an event ?
Yes. Consider having a look at UnityEvents or Actions
This is a simple C# event public event Action SomeEventName
You can invoke it from the same class
But not outside
What's the problem in invoking it ouside of the class since it's public?
I'm pretty sure it doesn't allow you to? At least in my memory
I'd need to check again
It does.
You can indeed invoke an event from the another class.
AnotherClass.SomeEventName?.Invoke();
ok i just read some documentation, now how do i get the event to be called 60 times per second
or to be called at a 0.0167 seconds interval
Or should be called at a 1 / 60 seconds interval. Use WaitForSeconds(float seconds)
i don't see the problem with using FixedUpdate at 60hz for this, if the framerate goes below 60 it'll just run multiple updates per frame to catch up, it's designed for that
I don't think they want to run all the objects at the 60 fps.
for a fighting game with deterministic gameplay, surely yes you do
They have just mentioned calling a single method at the 60 fps
Coroutine is enough.
i don't know why you'd use a coroutine specifically for this, a coroutine is also limited to running in the same fixed update or update loop, but either way you'd probably want to implement some kind of fixed timestep if you're not using FixedUpdate directly
Why would I not use a coroutine specifically for this?
if it's running forever in a loop, why not just put it in an Update method somewhere?
This seems the best option. And more comfortable than using Update with Time.deltaTime added to a variable
And it's also so that you won't be able to call a method 60 times a second in your Update if your game's fps is smaller
WaitForSeconds also only works if your framerate is 60 or higher
Yeah, you're right
You may use whatever you want, but coroutines are usually much more readable.
Next Level Debugger 😄
ah. i'm a really sucker of code
||i'm correct but why error problem here? maybe who can fix i really tired of fix problem error but found on yts||
Error on line 12 as the error says. Missing a ; at the end of the line.
And I'm not going to comment on the fact that you're still using JS even though it got deprecated years ago
if i want to execude code after animation finishes, do i have to use events or is a timed Invoke enough? accuracy is important
Animation Events. That way if you modify the animation you don't have to change a "magic number" in your code
Or state machine behaviors, which have a method that gets executed when the state it's attached to exits
youre right
How can I draw gizmos on the plane that I created in script? For example, Plane plane = new Plane(Vector3.up, Vector3.zero) and I want this object to be visible by Drawning gizmos. Is this something stupid to want it and should I try something else? I have no idea but this is my intention to see it. I hope I was clear to describe my problem.
should a GameHandler be a singleton or a static class?
almost nothing should be a static class
other than utilities like Mathf
with pure functions and no state
thank you
'MonoBehaviour' instances must be instantiated with 'GameObject.AddComponent<T>()' instead of 'new'
public Dictionary<int, WikiPost> WikiPosts;
public Dictionary<string, WikiUser> WikiUsers;
private void Awake() {
//Day 1
WikiPost testPost = new WikiPost("title", "desc", Texture2D.blackTexture, null);
WikiPosts.Add(1, testPost);
}
public class WikiPost : MonoBehaviour {
public string postTitle;
public string postDescription;
public Texture2D photo;
public List<WikiComment> postComments;
public WikiPost(string title, string description, Texture2D postPhoto, [CanBeNull] List<WikiComment> comments) {
this.postTitle = title;
this.postDescription = description;
this.photo = postPhoto;
this.postComments = comments;
}
}
``` can someone help?
i want to make a dictionary of WikiPosts
You can't do new WikiPost since WikiPost is a MonoBehaviour
pretty straightforward error
Is there a good reason you need WikiPost to be a MonoBehaviour?
if i think about it then no, scripts will get the posts from the game manager
Since there is no good reason for WikiPost to be a MonoBehaviour, you should make it not a MonoBehaviour
thanks, I will move all static functions to another static class like FMath then
also i have a question how can i make an enum dictionary, where e.g theres "someUser" = WikiUser("someUser", Texture2D.blackTexture) and so on
Make Dictionary<MyEnum, MyDataClass> I guess?
vague question
like i don't want to make new users each time i want a user to be referenced, so i want them to be made once and referenced in other scripts
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I meant like I'm starting to feel alright from the break I took from this whole coding thing here
Yo ! I want to give to a method a data structure that is able to have a variable and a value. In this method there will be a loop that will go through the data structure and will set each variables to their respective values. BUT I want the original value to be changed not a copy of the value (If it was in C I will give a pointer to the variable). How can I do that please ?
is the "data structrue" struct or class
if it is struct then you can pass it as ref=pointer to the variable
I'm not specifically talking about a struct, for instance it could be a Dictionary or a Tuple but as I saw it copy the variable :'(
Alternatively, you can have a "Wrapper". That being said, it is usually not a particularly good idea to change a value this way.
Oh ok...
By example, there is the functional paradigm that specifically handle all case with a return.
Cool... so did you have a question? Or just making that announcement?
I am glad you feel better though
dictionary is class, but you can still use ref to pass it as pointer to that dictionary
My goal is to add what I just said in the message at the end of this method. The idea is to set a number of variables to their respective values when an animation end.
https://gdl.space/wewajozehu.cs
I want to do that instead of using animations Events because I feel like adding each time an event at the end of an animation and defining a specific method to handle what happens at the end of each animation is not really sustainable. Tell me if i'm wrong.
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Use StateMachineBehaviour to handle end of animation instead of inspecting the current animation.
https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
And, I am not sure what you actually want.
I want to check if a specific animation has ended, if it's the case I want to set a bunch of variables to a bunch of values. For example : Let's say I have a roll animation, I want to wait for it to end and then set for example IsAbleToRoll = true, Blabla = false, Toto = true, etc...
You should have a "DodgeState" that register on an event of a StateMachineBehavior that invoke the event whenever the animation state has ended. Then the DodgeState would handle everything it needs to handle whenever the animation end.
Are you familiar with what events are ?
I will look about the StateMachineBehaviour, I don't know what this is and I will come back here if I have questions 👍
Yes
Good, because it looked like it was that you were missing.
I know that you can set events in the frames of an animation, but I don't want to use that because it doesn't feel modular and scalable
That is not what I am talking about though.
C# events
Oh okay, yes I also know then
public event System.Action MyEvent;
I'm not a pro at it, but I know the basics
Yes, you can Invoke it and subscribe to it
What you were asking, the usage of "pointer" can usually be done with events.
How do I programmatically change the sensitivity for a cinemachine virtual camera using the POV Lookat and Framing Transposer follow
But a StateMachineBehavior in my case is close to being the exact same thing as just setting an event in the animation frames ?
But just done by code instead of being done by the Unity inspector ?
Yes and no. It is better then reading the current animation and prevent issue with transition that could make an animtion not trigger a "mandatory" animation event.
Ok, so I should avoid my initial idea and go for that ? But this means I will need to create a specific StateMachineBehaviour for each animation (if I want to process something at the end of it ofc) ?
make the reference, access its properties
AnimationState, foreach animation state that needs that.
problem is I have no idea where this reference is, cinemachine docs have nothing for me and I can't access the speed variable in code
the docs have nothing.. ?
i find these statements pretty wild lol
nothing that I've been able to find on changing the speed the camera rotates with
Do you mean StateMachineBehaviour by AnimationState ?
are you looking at the cinemachinevirtual camera api ?
show me where you looked
Yes
Ok, thanks for the infos ! Really useful 👍
literally
Accel Time The amount of time in seconds it takes to accelerate to Max Speed with the supplied axis at its maximum value.
and
**Max Speed** The maximum speed of this axis in degrees/second.
can't find said property in code
it's not an exposed variable as far as I can find or it is confusingly named
https://docs.unity3d.com/Packages/com.unity.cinemachine@2.3/api/Cinemachine.CinemachinePOV.html
all the properties are here
api is the scripting
manual is just the general info
yeah I just found it, but still no info on speed it seems
speed is acceleration time / maxspeed
So I'm basically trying to add a feature where you can change the camera sensitivity, I know how to do this in editor from the inspector but haven't found how to set it in code during runtime
inspector of what, show what ur changing
generally sensitivy is custom float made for custom rotation
I barely use the POV
I'll get you a screenshot now
I just use regular cinemachine virtual camera, and rotate that
So I am delving deeper, it seems AxisState is yet another class with it's own references
thanks, well... before that I think we were talking about github and the character respawn problem
You notice how it says Max Speed
as MaxSpeed
cinemachineVirtualCam.GetCinemachineComponent<CinemachinePOV>().m_HorizontalAxis.m_MaxSpeed = 123;
hmm i guess you can try axistate
thanks for the help
I should be able to manage from here, my main problem was just finding the variable.

@steady moat I did what you said, using the AnimationState and it works perfectly. I just don't like the idea of having to create a separate script for every animations, but this system is still better than all of the others. Thank you very much !
You only need to create one script for the AnimationStateBehavior though.
Yes, but if I have a roll animation and a backstep animation, I need to create one for each right ?
No. You just need to attach the same script on both.
That could be a way, but I suggest you either use string, enum or type as "id".
But let's say I want to invoke OnRollAnimationEnd if the roll ended and OnBackStepAnimationEnd if the backstep ended, how should I differentiate which one ended if i'm using only one script ?
public class AnimationDodgeEvent : AnimationEvent {}
or
public class AnimationEvent { [SerailizeField] private string id; }
huh?
buttonScript.profilePicture.sprite = Sprite.Create(post.PostCreator.ProfilePicture,
new Rect(0, 0, post.PostCreator.ProfilePicture.width, post.PostCreator.ProfilePicture.height), new Vector2(0.5f, 0.5f), 100f);
``` the ProfilePicture is Texture2D.redTexture
public class AnimationEvent
{
public enum MyEnum {
Dodge,
Attack,
etc.
}
[SerializeField] private MyEnum enum;
}
And I do for example AnimatorStateInfo.IsName(rollName) for example ? (if it's a string)
No.
I'm having a hard time following here sorry
public class AnimationEvent : StateMachineBehaviour
{
public enum Event {
OnEnter,
OnExit
}
private static Dictionary<(string id, Event evt, Animator animator), System.Action action> subscribers;
[SerializeField] private string id;
public static void Subscribe(string id, Event evt, System.Action subsriber)
{
subscribers.Add((id, evt), subsriber);
}
public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
if(subscribers.Contains((id, Event.OnEnter, animator)))
subscribers[(id, Event.OnEnter, animator)].Invoke();
}
}
Something like that.
You can figure out the details on how to make it works.
Thanks for thid ! I can't look at this right now, I will tell you when I can 👍
Ideally, you might want to seperate the actual event and the subscription into two separate class.
Yes thanks 👍 I dont want the code, I prefer the idea behind it
Is it a good practice to include ALL font assets into the font fallback chain, just in a correct order, starting with static and ending with Dynamic for more obscure characters?
So, you will put this script on every animation that needs to have a StateMachine ?
anyone know how to detect/and or resolve packages that have changed to their default state? Client.Resolve() doesn't seem to do this. Client.Add(URL) works (git packages won't be reverted correctly with anything other than URL, not sure about others), but still not sure how to determine if they've been modified.
Yes. AnimationState.
Ok thanks, I guess I understand the idea behind it.
Hi guys im looking for a bolas like system i have a gameobject between 2 gameobject with rope and i want to rotate the midle object and other follow him someone can guide me to something pls ?
who's other to follow him?
the 2 objects around
You can make ropes out of chains of connected Rigidbodies with hinge joints
Or you could use an asset like Obi Rope
yeah hinges will do. ObiRope looks cool
ok thx guys i will search on that
just want to check something before I do a stupid:
public class Target
{
public void Hit()
{
// do smth
}
}
public class Enemy : Target
{
new public void Hit()
{
// do smth else
}
}
hit.collider.gameObject.GetComponent<Target>().Hit()
Would still do smth else instead of do smth if it hit an Enemy right?
if I overrode it then it would work how I expect?
Yes
oki noice
If you don't plan on having any logic in Target.Hit(), consider making it abstract
I do but good to know for the future
if you have an Enemy variable and you call Hit() you will get do smth else
If you have a Target variable and you call Hit() you will do smth
if you did a proper override... oh SPR2 sorted you out
But you'd get do smth else in both cases if you override properly. (assuming it's actually an Enemy)

To create a speed effect in my 2D game, I want to stretch and shrink the player's view in the direction they are walking. How to do it?
In the editor, when you drag an object into your scene, it snaps to other objects that the mouse is hovering over, without overlapping them. Is there a way to replicate this functionality in a runtime scenario?
I've been doing research to try and find something like it, but I can't seem to find anyone implementing something like this.
i use this scriped for playing animations walk1 is a walking animation ,walk is a idle animation but when i pres a and d both at the same time it doesnt go back to the idle animation(walk): if (Input.GetKeyDown("d"))
{
Debug.Log("hi5");
transainimation.SetTrigger("walk1");
}
if (Input.GetKeyUp("d"))
{
Debug.Log("777");
transainimation.SetTrigger("walk");
}
if (Input.GetKeyDown("a"))
{
Debug.Log("hi");
transainimation.SetTrigger("walk1");
}
if (Input.GetKeyUp("a"))
{
Debug.Log("888");
transainimation.SetTrigger("walk");
@cunning meteor dont crosspost
alr
how do you serialize a graph that has references to gameobjects in a scene ? im using callback reciever interface, i dont know how to keep it all linked
That is a mechanic often seen in building games like RTS, TD, etc (you can try looking up these genres for more research), though the general idea would consist of firing a raycast from the mouse screen position to the world position, and placing an object at the hit .point, if the pivot of the object is at the base then that should be all youd need to do, if it is in the middle, youd want to consider adding half the height of the mesh bounds or collider bounds to the hit .point before placing it - you can take it one step further and snap it to some kind of grid if you dont want to allow freeform placing, RTS games tend to do grid snapping, TD games tend to allow freeform since RTS tend to be about managing limited resources and TD tend to be about maxing the landmass, but every game is different
So as long as I have a pivot point, just use that? That's much simpler than what I thought I'd have to do, (Nonsense involving rigid bodies).
Thank you!
In my case, I'm planning on using it for a Spore-Style Item Crafter.
I just need to make sure that all of my items have some kind of definition of where their pivot point is.
Sounds cool! But seems like you got th general idea, yeah - though if the object does have a rigidbody and you dont want the thing your placing to move around aftter placing it (or you want to create a "preview" or "ghost placement" to see where you would place it without committing to placing it there), you may need to set your rigidbody to kinematic, sleep the rigidbody or freeze its constraints (or possibly disable the collider so physics dont have anything to react to)
Yeah, all my items will be kinematic, since I do need them to not be influenced by physics
the rigidbody is purely for hit detection, in terms of its actual functionality
Raycasts can hit colliders without rigidbodies as well, so if you only need it for hit detection, you may not even need the rigidbody at all
List<SourceVertex> filteredVertices = new List<SourceVertex>();
List<int> filteredTris = new List<int>();
for (int i = 0; i < positions.Length; i++)
{
Vector3 vertexPosition = positions[i];
float vertexHeight = positions[i].y;
if (vertexHeight >= 5 && vertexHeight <= 10)
{
filteredTris.Add(sourceMesh.triangles[i]);
filteredVertices.Add(new SourceVertex()
{
position = vertexPosition,
});
}
}
Im trying to make grass on the GPU
and i have the array of verticies and triangles
however I wanted to only have grass for a certain height range so i was tryign to filter it
but when i added the filteredTris thing, my unity completly crashes
Unity editor crashes??
yeah
wait i think it might be a index out of bounds error
coz im assuming that sourceMesh.triangles is the same size as positions
The editor shouldn't crash even if your scripts throw an error.
oh
Where is that code running?
in a grass generator script
is the editor actually crashing or is it freezing? because those are two different things, and which the latter is usually caused by your code
that typically indicates an infinite loop
int[] tris = sourceMesh.triangles;
SourceVertex[] vertices = new SourceVertex[positions.Length];
for(int i = 0; i < vertices.Length; i++) {
vertices[i] = new SourceVertex() {
position = positions[i],
};
}```
this is the original code. The only problem is that it covers my entire terrain mesh and i only want it to cover over a certain height
so how would i go about doing it in a way that like works
I don't see anything that might cause an infinite loop here, but you can break with a debugger when it freezes to figure it out.
As for the implementation itself, I'm not sure if modifying a mesh like that is gonna produce the results that you expect.🤔
yeah i tried a new approach and it worked
if anyone has suggestions on this let me know
How many of these things are we talking about? I spawn VFX (with instantiate, from prefabs) as needed and haven't run into problems with .. hundreds of them even, per frame? Maybe the object pooling overhead isn't worth the gains
Like obviously object pooling is great for things like bullets that are relatively "simple" with limited logic but you're spawning potentially millions of them over a session.. but even for vfx, I dunno, it seems like maybe it's a close call whether the additional complexity and load costs are worth it
bullets I'd say are good pooling candidates, but .. maybe the other stuff isn't until you're talking like N > 100k+ in a session..
i dunno .. like in my merge game I create several items per turn that have lots of initialize logic.. shaders.. material cloning.. vfx and particles, sound clip allocation and playing.. and it's pretty invisible even when the user is mashing moves at 2-3/sec
even with editor overhead i've never dipped under 60fps or any GC burps
i tried to mash through that level as fast as i could to demo
its hard to estimate since i havent planned a whole lot but definitely not near 100 a second. im making a roguelite, enemies likely will cast abilities every few seconds, planning on having a max of like 50 enemies at a time.
I probably dont need pooling, but im also scared of running into a case later when im really deep into the project and suddenly start needing it. Then having to implement it on everything
each one of those tiny little prefabs has like.. 500+ lines of init code, instantiating and copying materials, vfx, nested prefabs etc.. and i've just never needed to touch optimization
I'd probably KISS here and not pool until it's a problem
object pooling is great but it's definitely adding a layer of complexity when the cost/benefit might not be clear at the outset
imho stuff like this (maybe even localization) is best added when you need it
i don't even think retooling to take an Instantiate() approach and moving to a pooling approach is that big a deal
Ah you're probably right. Ill likely just drop the pooling entirely for now because this really is such a pain. Im pooling an object thats likely gonna be cast once every 10 seconds
and if you get to the point where you are seeing some performance issues.. at least at that point you can crack open the profiler and examine what's going on.. maybe some errant Resources.Load() call you forgot about or whatever.. and if you just can't get any faster then.. explore the pooled approach imho
yeah overengineering a perfect solution is a ... tempting forbidden apple in gamedev.. my opinion is that you kinda gotta get something into market/finished before you worry about the tech stuff like that.. even accruing some tech debt with the benefit of getting shit done is worth it imho
like.. the other day my game designer asks me for a list of all the levels (some 600+) in our game with the 1-star/2-star/3-star moves required since the admin tool makes editing a single level easy but not reporting on all the levels at once
It just feels wrong to be instantiating and destroying so much, but maybe ill just run some tests to prove to myself its not a problem
my brain starts going.. ok, I can make some denormalized json reporting object that'll get uploaded to our reporting/analytics database, polled once per day.. plugged into google drive
and he's like NO NO NO do THIS
that code took like 4 minutes and he's like BEAUTIFUL I LOVE IT
and meanwhile i'm like 🤮
point is.. Instantiate() or even Resources.Load() aren't terrible in small doses, or even before you know you have a problem.. cuz kind of the worst outcome is you spend hours/days/weeks architecting something complex and beautiful and fully featured but then it wasn't even necessary
Yea true, i guess if i have problems itll likely be from certain overused attacks anyways which I can just make dedicated pools for.
not my one off, 30 second cooldown ultimate ability
or even if it's a huge problem, make the attacks like that use different kinds of bullets instead of 100x bullets
like a beam
(dunno exactly what your game is but hopefully you get the point.. like.. just change the ultimate a tiny bit to not need 1000 of a small thing)
"hit everything on the screen 6 times"
thats a pretty smart idea, just like a single beam and change the damage rate of it
yea my game is just a simple 3d roguelite, you go around and shoot things. items will buff the players and they'll likely get a lot of buffs to the point of possibly having 50x the initial attack speed
yeah maybe... depending on how many bullets every enemy is shooting at you (like, is this a bullet hell, or is it more like.. uh.. i dunno, something less ha) you might actually need to pool
Instantiate is expensive but .. not too bad, and having all the logic constrained to a single bullet/player/npc/turret without needing to do all the pooling "gimme a bullet and set it here and tell me when it hits something and set the owner/properties/speed of it" would be nice
if you are pooling, though, i'd probably just have a single pool for bullets, with a BulletManager static/singleton and some methods to get a bullet (and have the bullets do the collision checking and returning themselves to the pool)
basically your enemies/players/turrets/whatever should basically not have to do any of the plumbing - just "get me a bullet, set it to (x,y) with a velocity of (x,y) and a damage of (x)" and then forget about it
if you've played risk of rain 2, id say my game is gonna be comparable to that. Starts off slow, but overtime the player might be shooting 50 attacks per second. Each hit will also have effects where itll need to check through my inventory for effects like after dealing damage, apply an additional damage over time.
I mean.. obviously I could [over-]engineer the crap out of this little thing.. store the path in player prefs, prompt the user for it, save the output in a document and put it in the database, etc etc etc.. but the 10 line csv solution that took 5 minutes was what the designer needed/wanted and then we were back to other problems 🙂
Yeah so ... despite my previous diatribe I'd actually say you're probably on the right path (pooling).. I'd just make sure that you spend the effort on the bulletmanager singleton to make the api surface as clean/minimal as possible
whatever is shooting or getting hit by the bullet shouldn't need to do a lot of boilerplate nonsense to get/destroy a bullet
i dunno exactly what that looks like for you, but maybe it's a callback on "did hit the player" or some interface that all your shootable/hittable things implement in order to interact with bullets (ie class Player : IHittable, IShootable where hittable has a "GotHit" callback or something, shootable has some things like "shooting direction" or "shooting velocity" or "shooting damage" or whatever), then the player just calls Shoot() and the bulletmanager does all the repeated boilerplate code
yea but this kinda brings me back to the initial problem. its really annoying to populate this pool. I could populate it when its first asked for a certain prefab and really i might just do that but over time rather than instantly.
and yea the pool right now is also pretty easy to use, its a 1 line solution for anything to get an object. then the object itself is responsible for returning itself to the pool
why's populating the pool expensive? Aren't you doing this like, once per game session or level or something? I mean, I feel like even if your game is pretty "busy" you only need like.. 1k? 10k?? bullets in the pool
even instantiating 10k items in the pool once should only be a few hundred ms... maybe, depending on what each bullet needs to do
Hi I wonder if somone can help me pls? How do I change an objects physics layer mask after instantiation? The prefab is built as "ignore Raycast" for instantiation but then needs to be switched back to "default" after instantiation.
gameObject.layer = LayerMask.NameToLayer
or something
i mean that either i have to manually drag in each object to this pool in inspector, or I can populate the pool manager when something asks for an object for the first time. Basically a difference of doing it in awake vs doing it on demand. Im just unsure if doing it on demand will suffice, because throughout the game there will be new enemies so this will constantly be spawning 100s of objects as the game goes on
Hm, I guess I don't understand? Maybe show me a screenshot of your inspector pool or some code about how you're getting these pooled objects? It sounds like you're doing something (process-wise, not theoretically) incorrect
Like, don't you just have some class BulletManager that's got an Object Pool on it, you instantiate a boatload of the bullets at app/level startup, but then you just GetPooledObject() (or whatever the method is called) whenever you need a single bullet? .. you shouldn't be adding more items to the pool at playtime runtime unless you've suffered some pool starvation, in which case you'd need to just adjust up how many items the pool is making at the beginning
[SerializeField]
List<PoolConfigObject> pooledPrefabsList;
Dictionary<Component, ObjectPool<Component>> pooledObjects = new();
[Serializable]
struct PoolConfigObject
{
public Component prefab;
public int prewarmCount;
public Transform parent;
}
gameObject.layer = LayerMask.NameToLayer("Default") perfect, thank you
wait - are you only instantiatng "prewarm count" bullets?
right now the pool is just one pool with everything
bullets/explosions/hittexts etc
show me more code on your ObjectPoolManager - like, show me where you GetPooledObject
oh ignore the numbers used, i just default them all to 10 and was testing something with the 1. Itll be more
yeah it should be like 100-1000 i imagine.. maybe hittexts/explosions/healtexts are like 50, but bullets probably 1-2000
https://gdl.space/evirajukut.cs
this is the code
it works pretty nicely, but populating this in inspector sucks
Random, but I really like that you call it Singleton instead of Instance.
😅 sometimes i name it Instance, depends how im feeling that day
Unity does that for NetworkManager in NGO i start doing it too
just trying to wrap my head around it (sorry, I've actually never pooled so only understand it at a high level) - but ... shouldn't you be doing the instantiation of the pool yourself rather than creating the dictionary of object pool components?
Does anyone have any idea why my Heating subclass is not in use by any asset. The subclass is not separated from the base class by another script. They are both sitting in the same script which is already attached to a game object.
Like, I always thought you slapped an object pool component on something, then did the instantiation of the objects yourself, not create the component yourself with initializers to actions/funcs
Generally, you shouldn't have 2 MonoBehaviours in one file.
Like maybe I'm missing something obvious, but it seems like your singleton is creating an object pool at runtime, not populating an object pool that you've defined
right now, its a dictionary of Component to ObjectPool. There are as many pools here as needed. Other objects can request an object by already a reference to a component on a prefab.
and it does get filled through the create function line 63
Like why not just make an Object Pool that has some RBProjectiles on it, you instantiate your 100 or 1000 at awake time, then everything in the game just says RBProjectileSingleton.GetMeABullet() and the singleton just does RBpool.GetPooledObject()
it doesn't look like that to me? it looks like lines 63-75 create a function that you send as a parameter on line 95
Then what's the solution, separating them in two files? Is there an alternative to that. I am only using inheritance to override a specific method
so your singleton creates an object pool that is empty and not initialized
the pool itself works and has all the objects that i want, its just that it is tedious to assign the references for which object it should spawn in inspector
yes, keep one monobehaviour per file. that's only part of the issue though, the other part is that you don't have that component attached to any object (which is also impossible while it is in a file with another MB)
hm.. ok.. I'm probably missing something .. not sure what though 🙂 Sorry that's not more helpful
Separating them into separate files. Back in the days, unity wouldn't even allow you to use them as components while in the same file.
At a glance though, it does seem a bit more complex than needed - aside from bullets.. like I'd use hittexts and healtexts and VFX like explosions just as needed until playtesting shows otherwise
it definitely is weird code to look at, which i mostly got from here https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/object-pooling/
But i will still take your advice and not pool most vfx
i have this hittext thing which I'm assuming is pretty close to yours.. basically you spawn it at some location and it just rises up over 0.5f sec and tweens the color from whatever to whatever... does some material stuff, some random angle/heights/etc so they don't overlap.. i've spawned hundreds of them on the screen at once and it hasn't been a hotpath thing
I figured Unity would be able to attach both classes onto the same game object but I was wrong, man that sucks
Yikes
I'd probably rearchitect your singleton to just be a bullet manager - and the api surface the rest of your game essentially consumes is public Bullet GetBullet() and then returns it to the pool with bullet.gameObject.SetActive(false) which, my understanding, is how you do it (instead of destroying it)
you can do it at runtime, but if you want to do it in editor using the Add Component menu then you have to make sure that you only have one monobehaviour in the file, and that it is the class that matches the file name (unless there are no other classes in the file then the filename doesn't have to match in 2022.2+)
pretty similar but i didnt do that angle/height thing. Just moves up and to the side randomly
Can anyone help me with my textures theyre messed up
at least that way, you only have to "solve" the pooling problem once, and the rest of your game ultimately doesn't care about how a bullet is created/destroyed
Wdym by attaching both? And what's the point of it? The sub class already includes the functionality of the base class.
here i am, smoothbrained putting one class into multiple files, not putting multiple classes into one file 🤯
😉
Heh, poor C++ coders have to split each class into 2 files.
I learned on C++.. PTSD from .h files
I'm not sure if I'm understanding the question correct. At first, I had separated the base and sub classes into two separate scripts. This gave me a problem because all the variables from the base class were carried over to the sub class which then Unity needed me to instantiate in the sub class. I don't need that because that are already instantiated in the base class.
maybe my initial message was a bit unclear, the pool itself was already done and it works. its just tedious to use. But i feel itll be less tedious now if i dont pool every single thing. Im not sure if i can really make a single bullet manager, because a lot of the projectiles will be unique. Like some use raycasts to hit, some use rb and physics
I'm a native C# developer, I am just not good at it lmao
this is a code channel
What variables exactly are you talking about?
where do i go?
I suppose I should use the word "field" instead, but all these
Kinda hard to say anything without seeing the code and errors/issues that you had.
Fair
These are class fields, so they need to be assigned/initialized per instance of the class. I don't see how that is related to inheritance.
regular classes and structs can have as many as you want btw in one file, its just Unity and MB that doesn't like that
Because I have a method that I want to override to remove its functionality
Actually
Oh my lord
I can just use a bool to get it fixed
And then do an early return
That's fine, but I don't see how it's related to class fields and why that would make you put both classes in the same file.
Also, if your child class does not use(does not need them assigned) any of the fields in the base class, inheritance is a very poor choice imho.
I want to remove the functionality from these methods based on a certain condition, I figured I'd just override them solve that problem
I figured 😂
I'll just use bools to get it fixed
I have no idea why I didn't think of that
I struggled with this for over a day
I am actually angry now
But thanks for helping
Hi. I want to make a client for a multiple unity games, but they should be embedded inside (unity window inside client window). What engine can I use for the client? I cant find a solution for unity game inside unity game, wpf seems to work only for windows, and flutter only for android and ios.
heyy could anyone help me with a bug Im having in a 2d platform game?
Maybe. What is the bug? What have you tried doing to resolve it?
Thanks, basically I have a moving platform and a Player, when the player jumps on top of the moving platform I check the colliders and I parent the moving platform to the player so they both move together, however when I try to move the player the movement is all stuttery
I have tried adding the velocity of the moving platform to the player, however its slow and stuttery
Yeah, pretty standard.
What are you doing for movement of the player?
And what do you do for the platform?
private void FixedUpdate()
{
_onGround = _collisionDataRetriever.OnGround;
_onMovingObject = _collisionDataRetriever.OnMovingObject;
_velocity = _body.velocity;
_acceleration = _onGround ? _maxAcceleration : _maxAirAcceleration;
_maxSpeedChange = _acceleration * Time.deltaTime;
if (_onMovingObject)
{
_desiredVelocity = new Vector2(_direction.x, 0f) * Mathf.Max(_maxSpeed + _collisionDataRetriever.MovingObjectVelocity - _collisionDataRetriever.Friction, 0f);
}
_velocity.x = Mathf.MoveTowards(_velocity.x, _desiredVelocity.x, _maxSpeedChange);
_body.velocity = _velocity;
Debug.Log(_body.velocity);
}
I check if Im on moving object, if yes, I do a new desired velocity, where I add the movement speed of the platform
_desiredVelocity = new Vector2(_direction.x, 0f) * Mathf.Max(_maxSpeed - _collisionDataRetriever.Friction, 0f);
for obstacle move, i have a parent which holds the script, a child that is the platform itself with rigidbody etc, and a list of points in which platform goes to
Ok, so fairly complex movement, but rigidbody velocity based.
im trying to make a name tag that follows my player, im using text(TMP) but nothing working. ive looked up stuff on yt and cant find anything. heres the code i have right now ``` public class gotocat : MonoBehaviour
{
public GameObject cat;
public Vector3 moveup;
public float up;
// Start is called void Start()
{
moveup = new Vector3(0.0f, up, 0.0f);
}
// Update is called once per frame
void Update()
{
transform.position = (cat.transform.position + moveup);
}
}```
yeahh and I think the fact its rb velocity based is screwing something up
Have you set the players rigidbody interpolation setting to interpolate?
yes
cant you parent the player to the tag?
i can try that rn
it already is
at least i think it is
Without testing, the code looks fine. Perhaps it is responding to external forces. Have you frozen any of the positions? Try that, it won't affect your scripted movement, only responding to forces applied externally.
If you want external forces, try freezing them only when on the platform?
No, still the same, if anyone could come voice chat I think it would be easier to show, thanks for the help
How do i make it so when i do fullscreen, the healthbar stays like realtive in size and stuff
Take a read on Canvas Scalar component and the different scaling modes, and see which one is the one you want.
check pin inside #📲┃ui-ux
thx
Yeah this fixed it, I can't believe I went through so much hassle for this 💀
Ignore the access modifiers
Using switch on (presumably) a bool is, unconventional to say the least.
lol ohmy
Why do you say that
Unconventional in what way
In that you can just use if.
I'm aware, I don't really use them unless I have to
but why would you use a switch statement here instead of just an if statement? 🤔
Because I am stubborn
That's literally the only reason
that's not an answer as to why you chose to use a switch statement
that's why you refuse to switch to an if statement
lol wut
seems more like someone just learned what a switch is 😄
ah yes, extra boilerplate. such aesthetic lmao
thats actually so funny
I come from Java
well when you've got a hammer, every problem is a nail
Maybe that explains
java has if statements
you are using an if either way
Sharplab link https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLuQb2XWPQCMB7cgG3QEMBuIktTAFnQFkAKASjyRLpCAwSQDOAdwCWAFwDGACy60++ObTEBTdDIBOAV00hMcAJzKe9TAHYrAXybEHSZM6A=
I meant it as a joke because Java has a lot of boilerplate code
These mobile controls do not work, the textures are white and can’t move, is there a way to fix it?
Put some effort in providing information. Especially when in code channel, which this issue does not really seem to belong
Probably UI for a first attempt and see, if its related to that. but still, put more info. Does it work in editor, did you try anything to debug yet and so on.
Okay.
I think the scripts are broken or something, I opened a deleted Rip-off game I had for years and it just showed up like that.
you know how to debug? like check the console and so on?
Not sure, I’m kinda new to scripting in unity.
#💻┃code-beginner is your channel then. And some unity basic tutorials on learn unity com or similar
You first check yourself, if you get any errors and if its working in editor and so on. investigate to provide something people can work with
so we should stop spamming this channel here. and its def. not a coding issue. your game is super outdated. Google for the error, short said, your systems used are no longer being used by newer editor versions. #📲┃ui-ux
Ohh.
anyone have experience with github? I'm having issues to the point where I cant work on my college project at all and its stressful 😭
Not sure if this is coding related. And without ANY information except, you have an issue with github, does not help anyone to help you
#1157336089242112090 with the version-control tag and an actual question
I was just asking if anyone had experience with github as an preceding question jeez, also I know it's not exactly code related but I wasnt sure where to ask @plucky inlet
This site explains their response
https://dontasktoask.com/
You should just skip the preceding question
No one wants to commit without knowing what it is about. Nor should they
The "is anyone experienced" question is just always harmful
Hope that helps! Nothing mean was meant by it
That's fair, well anyway then, it seems like I'm not able to fetch the origin because of some interuption that happens mid-unpacking process. I already tried restarting my computer and router, as well as logging out and back into github desktop so I'm not sure what to do. I can't work on classwork without it so I'm a bit stressed apologies if I came off rude at all. Also, this is one of the error codes I got: "remote: Enumerating objects: 45, done.
remote: Counting objects: 100% (29/29), done.
remote: Compressing objects: 100% (7/7), done.
error: RPC failed; curl 56 Failure when receiving data from the peer
error: 1435 bytes of body are still expected
fetch-pack: unexpected disconnect while reading sideband packet
fatal: early EOF
fatal: unpack-objects failed"
@dense swift here you got the right channel to ask for with the tag. Ask there and explain, where this error is coming from, cause its not a unity console error I guess.
Does anyone know how to make it so when I pause a Timeline, the animations on Animations Tracks animating the characters keep looping instead of freezing, here's the snippet of code that is pausing the Timeline:
public override void OnBehaviourPause(Playable playable, FrameData info)
{
if (firstFrameHappened && Application.isPlaying)
{
//director.SetSpeed(0d);
director.Pause();
unpauseAction = () =>
{
//director.SetSpeed(1d);
director.Play();
dialogSystem.continueEvent.RemoveListener(unpauseAction);
};
dialogSystem.continueEvent.AddListener(unpauseAction);
}
firstFrameHappened = false;
}```
I have been, no joke, looking for a solution for 4 hours and none of the google results work, you guys are my last hope before I decide it's not a bug and it's a feature
here's how the timeline looks
4 hours, hm? https://forum.unity.com/threads/pause-timeline-but-loop-active-animations-possible.638404/
like I said, none of the google results work
already saw that thread like
10 times
ALTHOUGH
maybe I could download the project of those examples
(which I didn't do because it was like 7 years old and it would be a hell to import)
If you say, it did not work, what didnt work? Any errors? Any outcome of your research?
for (int i = 0; i < GameDatabase.Instance.ItemList.Count; i++)
{
button.onClick.AddListener(() =>
{
Game.Instance.inventoryManager.AddItem(i);
});
}
Seems like this works like in JS and all butttons will call AddItem() with index being equal to .Count
How do I make sure that each button has its own index passed through onclick event?
copy the i to local variable
or make a custom struct/class and capture the variable by your self
Your code currently adds a listener to one button for all items?
Why not make the button a prefab and create it from script, so you already have a loop you could hook into and pass in the correct item?
Ah no, I just removed all of the code, I create an instance of a button from a prefab.
so you got it working?
Yes
That wasnt the issue, I did what the other person said and created a local variable.
Quite a common problem in a lot of languages
Go specifically added a language level fix for this problem somewhat recently.
there is no remove button in the package manager. does anyone know how to remove the package. we want to remove photon
how did you add it?
from package manager
Regular assets don't have a remove button. Only packages
You basically just delete them manually
For clarification regular assets are what you're importing from the My Assets tab
Almost everything else is a package
If its only in your project folder but not in package manager, its an asset and you can get rid of the folder
Anyone know how can I load dlls at runtime and add it to the project like if I have a assetBundle that as a script in a gameobject called Potato.cs and I compile that script outisde of the main project then import it with assembly.load how can I make it be acessible in the unity project. Because I want to make my game moddable more or less like KSP or city skylines.
It's easy and complex at the same time. Look into BepInEx
I'm sure you can implement it directly
Tho it doesn't have sandboxing
You guys got an idea about why ToJson might give me {} in a custom editor script but not on runtime? Like, the object is there and I can access the list, but ToJson does not seem to like the list when in editor mode. Is there a parameter I am missing to make JsonUtility work in editor scripts?
what is your object?
JsonUtility is pretty weird. Plus most people just use Newtonsoft.Json as soon as something doesn't work
It is a List of a custom class. But its serializable as it is working in playmode
Are you trying to serialize a List<T> directly? You have to have a wrapper object containing the list.
Ye, just trying out the jsonconvert of newtonsoft if it may fix it. Thought just out of curiosity, if the utilitiy might be capable of
Uh, dang, I totally forgot about the List root object thing 😄 I will look into it right now, thanks. That just might be the issue.
public class JSONWrapper
{
public List<MyItem> allPresentations;
public JSONWrapper(List<MyItem> newList) => allPresentations = newList;
}
Thanks again, that was the issue. Been 2 years since I ran into this last time 😄 Nice call 🙂
JSONUtility's shittyness strikes again
From what I could understand BepInex is used to add mods to already existing games not make a moddable game right?
What I want to do is import the asset bundle and compile then add the dlls so they are recognizable in the scene of the asset bundle
i mean i did already answer this question in another channel before, but the answer hasn't changed 😛 you can't create new script types at runtime without workarounds like bepinex, the alternative is to implement your own plugin system for making extensible scripts
Ok, but how should I approach the creation of the plugin system?
because a lot of games don't use the approach of bepinex and compile the scripts at runtime one of the examples is KSP
and it uses dlls, asset bundles for the mods I wanted to create something similar so the players don't need to install third party things
you can do pretty much anything that isn't creating new unity scripts, so decide what you want modders to be able to customize and create some base interfaces in the game that modders can implement in a plugin
But a lot of games can add unity scripts It's not impossible to do it but I don't find how can I do it I'm trying now to build a asset bundle with a .asmdef that I read on a thread that could work
sure you can do it, you just have to hack some unity runtime stuff to make it work, which is what bepinex does
Yhea and that's what I wanted to understand
Simplest answer is, create a base class for your mods and when you load the assembly of a mod which uses it, you can load it directly
It's essentially what BepInEx does outside of injecting itself into Unity
And managing dependencies
BepInEx's plugin class is basically a MonoBehaviour. When the game loads, it loads all mods that can be loaded (have the base class and all dependencies satisfied) and add them to a manager GameObject. You can typically see it if you use UnityExplorer in a game with it
I was checking out the profiler and was noticing I was spending a lot of perf on my physics checks, (which I use to check what creatures are near the caster, there are a lot of casters)
and was wondering if it may be more optimal to just iterate through all the creatures and check the distances? or would this be more perf heavy
Depends on the number of creatures
And what physics check you are using
And also why a physics check
im using Physics2D.OverlapCircleAll
number of creatures is like uhhhhhhh
50-100 i think
linear scan how many times?
And how many casters ?
you could just have a vector distance on the creature that checks for the distance itself. good queston from Uri, why even physics
Cause that will multiple for each one
well thats what im wondering, but that would require a lot of iteration as well as grabbing the array of all the creatures
im using physics because its what I thought was the way to detect all the things that are near something
how many distances do you need? one to th eplayer for each creature, or multiple?
this isn't for the player, its also checking other creatures to see if it needs to switch state to fearing or hunting etc
If just distance is needed then a simple check will almost always be more performant than using the physics engine. If that is still not suitable you should look into acceleration structure such as a octree or a kd-tree or even a simple grid
your physical query cant help you to reduce search space, try reduce the overlap radius, if this not work then the only way is to use your own space partitioning/BVH, then perform nearest neighbor search
i realize i havent written my own BVH though
okay good to know then
i'll try the distance check
Also consider not doing it every frame or consider splitting the work over multiple frames
not async, just not in plain update 😉
What about the creatures just adding and removing themselves to a static list when in range for example and do a simple vector distance on themselves against the player? Any issues performancewise?
I was referring to the good old time-slicing technique. For example in our game we have on average anything between 6k and 10k shooting positions for the enemies to take. Obviously we don’t update each and every one every frame
So like create a class mod that inherits monobehaviour and Type[] modTypes = assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(Mod))).ToArray(); something like that?
it is linear scan, ever worse than using physical query to limit search space
well this isn't just to detect the player
but yeah okay good to know physics slow
Ah, just read your post again and you have multiple casters and multiple targets (creatures). Well from that part, I agree with having something like a grid system or similar
CommandInvokationFailure: Failed to update Android SDK package list. C:\Program Files\Unity\Hub\Editor\2021.3.37f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\cmdline-tools\2.1\bin\sdkmanager.bat --list
Error: Could not find or load main class Files\Unity\Hub\Editor\2021.3.37f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK\cmdline-tools\2.1\bin\\.. Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
I am building to quest3
isn't quest vr?
yep, rerouting to #🥽┃virtual-reality 😉
before:
var IsNearFear = Physics2D.OverlapCircleAll(transform.position, FearCheckRadius);
bool HasFear = false;
foreach (var item in IsNearFear)
{
if(item.gameObject.GetComponent<Creature>()){
if(Fears.Contains( item.GetComponent<Creature>().MyColor)){
scruffState = ScruffState.fearing;
HasFear = true;
}
}
}
after:
var IsNearFear = GameObject.FindObjectsOfType<Creature>();
bool HasFear = false;
foreach (var item in IsNearFear)
{
if(item.TryGetComponent(out Creature c) && Vector2.Distance(transform.position, item.transform.position) < FearCheckRadius){
if(Fears.Contains( c.MyColor)){
scruffState = ScruffState.fearing;
HasFear = true;
}
}
}
this is probably faster maybe hopefully
Oh my god, do not do a FindObejctsOfType everytime
Get a list going somewhere and your creatures register themselves to it. So you got something to iterate over
good idea ig
Also the trygetComponent. Just be sure your creatures have the script and your list being of type Creature. soy ou can save that call too
what "Fears" is?
dont tell me it is a list of >100 elements
"Fears" is the list of colors it is afraid of
its like 4 elements long, Color is an enum
list of 4 elements is fine
the previous version is definitely better, iterate all vs iterate some of them
also use the overloaded version of overlapcircle which takes a list as buffer
ah whats the overloaded version?
I suggest to just write the most performant of both versions and see, what your profiler does
If you do not need physics at all, you could just remove it entirely from your project. But if you need it, you can still try to use overlapsphere and update from there. But as you already tried with your casters and creatures, your outcome was performance issues, right?
[MenuItem("Build/Build Linux Game Server")]
public static void BuildLinuxGameServer()
{
if (!Directory.Exists(LinuxGameServerBuildDirectory))
Directory.CreateDirectory(LinuxGameServerBuildDirectory);
var report = BuildPipeline.BuildPlayer(
new BuildPlayerOptions
{
scenes = GameScenes,
locationPathName = Path.Combine(LinuxGameServerBuildDirectory, LinuxGameServerBin),
target = BuildTarget.StandaloneLinux64,
options = BuildOptions.Development, // currently this is the only way to see logging
subtarget = (int)StandaloneBuildSubtarget.Server
}
);
if (report.summary.result != BuildResult.Succeeded)
{
Debug.LogError($"{report.summary.result} Server build failed with the following details: {report.summary}");
return;
}
Debug.Log("Server build succeeded and is located at: " + Path.Combine(LinuxGameServerBuildDirectory, LinuxGameServerBin));
}
docker run --platform linux/amd64 -it --rm $(docker buildx build -q --platform linux/amd64 -f $(git rev-parse --show-toplevel)/unity/UnityGame/LinuxGameServer.Dockerfile $(git rev-parse --show-toplevel)/unity/UnityGame)
Is there a way of seeing logging (Debug.Log and/or Console.WriteLine) in a non-development game build? The only way I've found I've been any to see logs from my monobehavior is to set BuildOptions.Development for BuildPlayerOptions (see code above). When that option isn't present, I don't see logs anymore in the game server. Since I'm on an m2 macbook, it's unclear to me if that's because logging is silenced on non-development builds or if its because there's an issue running the binary
Did you test, if the default Application recievedMessage is outputting something for you at all in builds?
tbh, easy option. Implement your own Debug class and write log messages out using System.IO.File
I agree, thats the simplest way if you do not rely on internal unity logs
I… did not. Wait, do logs go to a log file in non-development builds? Like should I be checking a log file in my running container?
I’ll try this “write to a file” strategy and see if the application is executing monobehaviour logic.
Another option I’m going to explore is SCPing my non-development game server build into an intel based VM in AWS to cross check if my CPU is getting in the way
So I am talking about this one. Not sure, if outputs anything if non-debug, thats why I was asking if you tested 🙂 https://docs.unity3d.com/ScriptReference/Application-logMessageReceived.html
From what I know, debuglogs get fired no matter the debug bool is on or not for built. so that would work
I see. Lol, unity is quirky if this is how to check.
I was also thinking about attaching my ide debugger to the running container and setting a breakpoint to check if the game is working.
Right now the game is just one mono behavior that writes a log.
Also, depending on the build, unity used to write logs to an output.txt inside your built folder.
Not sure about the current way or if it still applies. I am always using IDE or any UI to output what I need
iirc you can use the -logFile <path> command line option to make the standalone player output a log
Hey, I am doing a drag item from inventory function and have the drag script like this. When it hits a certain hitbox it goes back to its original place. But I've ran into many problems, sometimes the items disappear when they get dragged after a change of scene, or the original position is never (0,0,0) (the items are attached to a gameObject) and after dragging it many times it starts shifting from its original place. Any help?
The draggable objects have the following components
UI on a backend game server? 🤔
But yea, thanks for the advice! Just got back so now I’m going to learn more about the non-development version of my build.