#archived-code-advanced
1 messages · Page 161 of 1
My thinking for using a separate class would be to remove the MonoBehaviour static methods like Destory() and Instantiate(..) etc.
Just so it is cleaner and would only have the things that are actually relevant
It really depends on the use case yeah, if you don't want the end user to be able to access .gameObject and other members derived from MonoBehaviour, then sure make a whole new class
Alright, cool I just wanted to make sure I wasn't doing something that would be considered 'ugly' or unintuitive code. Thanks! 😄
Hello,
Im Building a multiplayer game and there is something that Is not clear about Netcode.
I have the client totally separated from the server, so the server will do all the Logic and then the result Will be propagated to all the clients.
The question is, how can i call a server method from the client if they are totally separated?
Inside the documentation they explain the approach of client to client host, but not the client to dedicated server..
Should i declare the same method on the client without putting the Logic inside?
For 32 768 iterate 100k items for 3800ms it's correct ?
other thing more efficient than parralel ?
@alpine nebula you could try to state your issue using full sentences. I dont get any sense of what you just said…
why waste time say lot word when few word do trick
fully agree…
??????
Depends what you wanna do
Forget that i found what i was searching thks !
Anyone know how to put animations into a unity character?
probably have better luck in animation, unless you're trying some new homegrown procedural animations
Anyone know of a way to create and reference functions or events in editor. I'm thinking something like the same functionality as a scriptable object. The idea being for my dialog, each individual button can be labeled and then call something dynamically.
Use UnityEvent
or even just invoke an event.
Thank you very much.
well, not quite what I am asking. I am using the same system for navigation. I use a struct to pair a label to a command. the question is how to predefine the command in a way that is easy for level design. for instance, I want one button to be labeled north and make an event call that moves the player north. another button I want to have the player explore the space and trigger something else. What data structure could be used to predefine the events for referencing?
I've thought about setting up a enum and referencing a static class but the issue is what if I need to send data with the event?
unity event can do this - you just need a script that has those functions defined
Then you can hook your UnityEvent up to call the function
Otherwise you can simply create your own system in code e.g. with Dictionary<string, Action> or Dictionary<MyEnum, MyDelegateType>
alrighty. I'll take a closer look. thanks.
that's basically a Facade pattern. it works well for an singleton proxy . . .
Fun question for ya. I have a large number of classes that derive from others. I would love, for organization's sake, to put them all in one script, like so:
public abstract class TypeNode<T> : ScriptableObject
{
public class GameObjectNode : TypeNode<GameObject> { }
public class AudioSourceNode : TypeNode<AudioSource> { }
public class AudioClipNode : TypeNode<AudioClip> { }
...
}
but doing this means that when I try to save my scene, I get this error and some of the data does not save:
No script asset for AudioClipNode. Check that the definition is in a file of the same name.
Is there a workaround for this? Or do I really have to have each and every class in its own file?
You should have all your classes in separate files, it is usually best practice. But you don't have to, you can leave them in the namespace instead of putting them inside an abstract class
I think that unity does get confused if you put them in the same script as a scriptable object tho, so you should make a new .cs and put them all in there
Every Monobehaviour and ScriptableObject must have its own file
Oh man, that fixed it. Thank ya
quick curiousity question
with a c# setter
why is the common pattern to use a backing store
instead of making use of the this keyword in some way?
what do you mean by backing store? having a private variable for the value?
class Person
{
private string _name; // the name field
public string Name // the Name property
{
get => _name;
set => _name = value;
}
}```
the example provided by .net
you basically have 2 types of get set, the empty ones like
public Field {get; set;}
and the other like your example
the empty one stores the value, while the other is actually just Methods
public float height {
get { return Mathf.Min(corners); }
set { height = value; }
}```
will this set work?
That's an infinite loop
not to my knowledge, which is quite experienced with c#
as I said, when you fill in the get and sets, it becomes only 2 methods disguised as a property
yeah i feel you
you don't actually have a variable in that case
oh
you just have 2 methods
i'll just do it this way then
public float height {
get { return Mathf.Min(corners); }
}
public float SetHeight() {
// stuff
}```
well, are you storing the height?
public float height {
get { return Mathf.Min(corners); }
set { /* stuff */ }
}```
as long as "stuff" isn't setting `height`
not truly
height is just a function of some other variables
it might be nice to think of it as a property but it's not strictly necessary
[System.Serializable]
public class TerrainCell {
public float[] cornersRelative = new float[4] { 0, 0, 0, 0 };
public float[] corners = new float[4] { 0, 0, 0, 0 }; //corners above 0
public float height {
get { return Mathf.Min(corners); }
}
public void SetHeight() {
SetCorners(new float[4] { cornersRelative[0] + height, cornersRelative[1] + height, cornersRelative[2] + height, cornersRelative[3] + height });
}
public void SetCorners(float[] newCorners) {
corners = newCorners;
for (int i = 0; i < 4; i++) {
cornersRelative[i] = corners[i] - height;
}
}
}```
just in case you're curious
should make cornersRelative read-only too
It is best practice to make get set fields with a capital letter like method names. Also, if you only have a get, you can simplify to:
public float Height => Mathf.Min(corners);
@hybrid ravine Not sure if you're still here, but that error is back and again it's not saving data. I really hope I don't have to have tons of individual scripts to define each derived ScriptableObject.
Hey guys, so I have a custom editor, and Normally I use SerializedProperty/SerializedObject, which means I dont need to set anything dirty. But this time my field is a custom class so I am accessing it directly. Though the logic I run takes place, the inspector window does not always register the changes. how do I go about reflecting those changes in the inspector? I tried:
EditorUtility.SetDirty(this);
Repaint();
ok so I have a list inside a class, how do I access it from custom editor as a SerializedObject
SO.FindProperty("list").GetArrayElementAtIndex(i)
one sec, let me try it
thx, that worked, but say I wanted to directly run a function from the targetScript. how would I go about reflecting the changes in the inspector also?
writing this in the inspector as a serialized object feels like a pain
and yes, I know I could loop it, but I mean a single line
You can put whatever you repeat more than once in a helper function. Doesn't usually matter if its SerializedObject or plain class properties.
Also, is FindProperty(string) more expensive?
yes it is, if you're doing it hundreds of times, you will likely have some Inspector lag (e.g. if you have an array with 100 tiles and do FindProperty multiples times for each entry).
Another reason why I should do it directly from the target script
but it gives you all of the implementation goodies. Without it, you would have to handle Undo and prefab overrides and potentially some smaller pitfalls like change checking and repainting.
Is there a comprehensive guide on all this?
If you're in an Editor class you should simply have to call Repaint() to make the Inspector redraw.
I mean, I been doing editor scripting for 2 years now and I still dont fully understand it
no, the class is on the target script
Not really. Unity's docs cover some topics, but its too much to read about everything in one place and also the entire system was not designed from the ground up to make perfect sense. It has a lot of glue and nails everywhere.
If that means you're trying to repaint the editor of a different instance, its more difficult. You could try repainting the window directly, but its difficult to get a reference to it. E.g. EditorWindow.focusedWindow.Repaint();
I tried that, didnt work
As far as I know however, if you do new SerializedObject(someOtherClassInstance).FindProperty("myProp")... bla bla and Apply, it will repaint the inspector for you. So before you find that performance is the real bottleneck here, maybe go that route.
Alright, cheers mate, I will give it a shot, my pc is 6 years old so if it works on it, it should be fine
If you're doing GUI.TextField(target.text) then that should always update if you repaint
If you're using serializedobjects for one bit and direct object access for other bits
Then you probably have to call Update on your SO
But htat overrides all changes you've made to serializedproperties of that SO instance
I'm not sure if this should be here or in #📲┃ui-ux but i was trying to build a Procedural Skill tree system that would list skills like this automatically. I'll just internally set all the skills that are a part of that skill tree and it would expand accordingly, my issue right here wasn't with the code itself but more with the skill tree's showing up in the UI properly.
So let's put it that i have 2 or 3 characters for now and i want them to be able to have different skill trees. The only way i seem to be able to setup the position of the icons is by either using a grid and forcing it to bee a bit too geometrical for what i'm going for or making the UI individually for each character (which defeats the whole purpose of it being procedural).
Does anyone know if there is a solution for me to adapt it via code so things will try to adapt and connect themselves properly and how viable they are? I could also code a whole method to just calculate the best positions for each square in a empty object and then calculate a path that can be drawn to it but do you think its worth the effort or should i just opt for doing it manually?
if its always the same layout and you need only 3, procedural makes no sense.
that's not procedural
not always the same layout. It will follow a tier/level pattern but wont be the same layout
the point is for it to be :/ tho i guess i could also be using the wrong word, english isn't my first language. All i want is the UI to generate depending on the skill tree that was created with the different skills.
Let's say i have skill A B C D E F and G
For char 1 i can go
A--B--C
|-D--E
But char 2 can go
A--C
|-D--F--G
|-E
i know it looks a bit of a mess in that example, but i'm not able to draw an example right now
but as i said i want the UI for that to be done through code, not manually
you'll have to elaborate on that
Does anyone have experience with with Blend Shapes, specifically with SkinnedMeshRender.sharedMesh. I'm trying to determine if it's possible to remove a single blend frame. I have a collection of vertex data to map into the shared mesh, and Unity seems to cache this somehow, but I need to retain a whole prebaked collection of blends, so I'm not sure if it's possible either to copy that data out and create a new massive collection to assign, or clear Unity's cache, or another solution. The core issue is that I can't replace a blend with the same name.
Solved: It was actually quite easy to just iterate through all the blend frame data and create a temporary list class to store all the original blend data inside, and when you are done you can clear all blends on source that were modified and replace.
Hey frens 🌞 anyone here has experience with GoogleCloudPlatform ? i'm trying to get to download my SSL cert.pfx or cert.json so I can put it in the VM and have my webGL client connect to it. But can't find anywhere on GCP where i can download either of those : /
I think you can do this in Unity’s UI using a horizontal layout group for the levels and a vertical layout group for the nodes in each level. The vertical layout group would be aligned to the center. The one thing I’m not completely certain about is how to do the lines…. though you can probably do it as a series of images that you scale algorithmically and parent to the overall panel itself rather than the layout groups, with positions set based on their connected nodes.
i thought about that but the issue is the lines themselves. but i thought there might be a better way idk about
yeah re the lines other than just setting their positions directly, i'm not sure. i would'nt be surprised if somebody has a solution for this somewhere but i don't know about it
You cannot remove a single frame, but you can get single frame data from an existing blend mesh, and also add blend shape frame to existing mesh.
You can combine these two to create a new mesh with only the frames you need. Other than that i dont think you have any other option
i transferred my project file from my old laptop over to my new pc but it seems to have broken the code
@tough tulip Thanks, I ended up just creating a temporary reference to all it's blends at runtime by iterating through the frames, and restoring the modified mesh back to it's original when completed.
Hey guys I need help, I'm making a Mobile/Pc Game called "Ultimate Hide And Seek" I need to make roles such as Hider, Seeker and Ninja, Hider is well a hider they can only hide, Same for the Seeker but he can not hide only find And now the Ninja Can hide, Go invisible for 5 seconds and stun the Seeker. I also need these to work with online multiplayer with cross platform
And ... you want someone to explain to you how to do all of that?
yeah im dumb
That's not going to happen here, nobody is going to take the time to walk you through an entire game.
If you have specific questions about your work, show it and ask.
ok so making the roles
We hold our breaths and wait for you to finish that thought
Watch some tutorials with a similar idea to yours and bring that learning into your game.
I've followed one tutorial and have learnt some pretty useful things
Hi folks. I'm currently creating a space exploration game and the planets and character are both rigidbodies. This is an issue because the mesh colliders of the terrain can't be attached to a rigidbody. Right now I'm just using LerpUnclamped to move the colliders to the planet's position and rotation. My primary issue is that the player controller doesn't move with the terrain, even without drag, and I tried using physics materials. I am not sure how I would transition a scene from a dynamic frame of reference to one fixed to a body moving through space
Enums
<@&502884371011731486>
I want to get into more advanced physics and graphics coding. I decided to take a crack at my own fluid simulation. I decided to create spheres and code their own physics solver so they have hydrodynamic behavior. My next challenge is to have the camera render them as a liquid. To do this, I was thinking of injecting the data into a graphics buffer and use a shader to determine their visual properties like, if they are fused together based on their proximity to one another, their volume (or thickness) based on how many are “fused” together, and other factors. I am going to use HDRP, and wanted to know if this is possible, and if this is a reasonably proper approach. If so, I never used a GBuffer and I have Shader Graph experience, but I don’t know yet how to have shader pull data from buffer. So this will be new territory for me and I wanted to get some guidance on where to start, maybe have some example code to look at?
Hello, I am having an issue with Assembly Definitions. scripts inside my Assembly Definition should be able to see namespaces inside Assembly-CSharp, but cannot. It can see things like UnityEngine, OdinInspector, etc., but cannot see my namespaces.
I have deleted and rebuilt my csproject files, and still get this error
Hello guys I have a question , I have a dungeon game , there are monsters and stuff but now I am wondering how should I impelement inventory system ,in youtube there are several system about inventory which one is more functional and better I dont know . Can you suggest me. its a 2d topdown game
is it cause a problem in run time ?
I can't even run my project because it won't compile, so yes
then it should be about packages , you sure imported correctly
There is no reason why I should not be able to see these namespaces, as the GIB namespace exists inside Assembly-CSharp
These are my scripts, there are not packages.
Hello guys, i am trying to stream a real camera video into unity and i want the lowest latency possible. Data comes from camera in JPEG over UDP. I receive them in unity and use LoadImage to load them into the scene. Problem is: loadimage is really slow. It adds 60ms latency to the camera’s 90ms latency. 150ms in total. If I stream over h264 (not to unity) I achieve 55ms camera latency
Is there a way to reduce the unity processing latency?
bump 😗🎶🎵
Optimistic, but ... has anyone managed to get a callback for 'AssetDatabase-will-refresh'? Unity's compilation crashes/throws an unhandled exception when multiple DLL's exist in the project with same name, which makes it a nightmare to import external DLL's, so I'm trying to create a script that will auto-rename them on import (script works 100%, it's just Unity that gives up, and then doesn't allow any more code to run)
I thought that anything inside an asmdef can only see other things inside other asmdefs, that was a core feature from the start? i.e. if you start using asmdefs, you have to use them everywhere.
This has been working just fine until recently. But even when I remove the asmdefs, I still get these errors
Folks, what's the best way to handle dev/prod environments?
Do you guys exclusively create dev builds and use #IF_DEVELOPMENT defines to handle dev env only code?
Any other practices I can follow?
your asmdef needs to reference the Assembly-CSharp assembly explicitly
How? it is not available in the reference list.
Do you have one?
Did you make one?
It's like @ivory salmon said you need everything to be covered by an asmdef if you're using them
Assembly-CSharp is not in the reference list.
Because you didn't create it
I didn't create what?
You need to put an Assembly Definition file (asmdef) in your main scripts folder to define an assembly for it
then you can reference that assembly from other asmdefs
My assembly having the issue needs to be able to reference scripts all over the project, so that won't really work
You're approaching things wrong then
Assembly-csharp references your asmdef, you can't reference it the other way around
Since circular references are not a thing
Let's back up - can you explain what you're trying to accomplish?
every folder that has classes will need an asmdef (or its parent ... grandparent ... etc will need one)
its all or nothing: use asmdefs, or dont use them
Ultimately I don't think I'm going to use them in this case.
the presence of asmdefs changes the way Unity builds your project (bit of a simplfiication, but broadly true)
It's very weird, though, because this worked up until recently, and stopped working for different members of my team at the same time, who were all working on different branches
ALSO: when changing asmdef setup, and there were ANY errors ... there are bugs in UnityEditor, such that you literally have to close the editor and restart it in order to see the actual error messages
Nah it didn't, asmdefs can't really reference assembly-csharp
I'm trying to implement an A* algorithm. I think I have all of the necessary information, but I'm kind of stuck getting further. Can someone take a look at my code at tell me where I should go from here?
Afternoon, Praetor
I think you should generally deal with Vector2Int grid coordinates 95% of the time. Vector2 should only be used for two things:
- Converting a grid coordinate to actual world space position
- Using that calculated world space position in your distance function
TIL that exists
Otherwise you're dealing with floating point precision errors in. your pathfinding logic which is nasty
That helps
Although wait is this a hex grid?
It is
Ok so you'll need to adopt a hex coordinate system
I probably should have tried my first implementation on a square grid, but as I understand it, A* is agnostic of grid type
there's a few options here: https://www.redblobgames.com/grids/hexagons/#coordinates
this is correct
as long as your GetNeighbors works consistently and properly then the grid type doesn't matter
I was recommended that site by a number of people on GDL, but to be honest, a lot of it is over my head. It's well written, I'm just slow.
Yeah it has a ton of useful info for hex grids
Does it have anything regarding converting Vector2 coordinates to hex axial coordinates?
Although I think I have a line that can do that
Vector2 newV2 = new Vector2(i * 1.5f, (j * 1.75f) + (i * 0.875f));
yeah
https://www.redblobgames.com/grids/hexagons/#hex-to-pixel
and
https://www.redblobgames.com/grids/hexagons/#pixel-to-hex
that's hex -> world and world -> hex
it depends on which coordinate system you're using
there's sample code for each type
When I'm calculating my G, H, and F, should I be using a raw distance or the number of tiles?
Yes
It depends on how your movement works
if your character can only move on tiles
and the distance is based on the number of tiles
then you use tile distance
But there's potentially a difference between your heuristic function in A* and the actual distance function. The heuristic is just used to determine which directions to check first
This isn't meant to be the actual map a player moves around on
Each tile represents a star system, and the player moves from system to system.
But they don't directly move on the hexmap, if that makes sense
So what's the purpose of the hexmap
To display the position of star systems in relation to each other.
And to help plot a route from one system to another.
Is it like, the player can only jump a certain maximum distance, so they have to find a path of systems which are close enough to each other to leapfrog across since they can't jump directly from origin to destination?
Have you ever played EVE Online or Elite Dangerous?
Yes
Which one?
Both. A lot more Eve than Elite
my condolences from a fellow bittervet
lol
You know how you can open the star map and plot a route from Jita to like.. Amarr or something?
Sure
And then it's a path based on the jump distance of your ship IIRC? But it's been quite a long time
Did ships have jump distances?
Subcaps don't worry about that, it's just capitals that have that, and they just have point-to-point jumping
Subcaps have to go through the gate network
That's where the routing came in
But you weren't hitting a button on the map that moved you from one point to the next, you have to fly to the gate, jump to the next system, fly to the next gate, repeat until you've arrived.
Anyway, this is partially for routing, to let player plot a route
But also for validation, to make sure there aren't orphan systems or systems you can't get to because it or its group doesn't have any neighbors.
Since each tile has a 1:X chance of just not existing, it can create tiles or tile groups that aren't connected to the rest of the map
So the pathfinding is intended to validate each system and make sure it has a path back to 0,0
Damn, he's got a hell of a lot more on there than hex grids..
if I add a function to a buttons onclick, do I need to worry about removing on destroy?button.onClick.AddListener(OnClick);
Yes
good to know. thanks
Does anyone know if Unity's raycast is non-deterministic? (note the camera transform is also constant)
float distance;
Ray mouseRay = cameraComp.ScreenPointToRay(Input.mousePosition);
new Plane(Vector3.up, Vector3.zero).Raycast(mouseRay, out distance);
Debug.Log("Camera Comp: " + cameraComp.GetHashCode() + ": INPUT<" + Input.mousePosition + "> + DIST<" + distance + ">");
Output:
Camera Comp: -827432: INPUT<(481.00, 495.00, 0.00)> + DIST<58.30573>
Camera Comp: -827432: INPUT<(481.00, 495.00, 0.00)> + DIST<58.31362>
Camera Comp: -827432: INPUT<(481.00, 495.00, 0.00)> + DIST<58.30573>
Camera Comp: -827432: INPUT<(481.00, 495.00, 0.00)> + DIST<58.31362>
...
So I decided to take the reflection route for my classes, @hybrid ravine. Now how to serialize and show the attributes I’m missing in the inspector?
I got the fields with a field array. Now’s just to set them onto the object with the for loop.
what is it you are trying to serialize? Sorry, I kinda forgot what you were up to
#archived-code-advanced message
Up here. The rest of the attributes that are only available in the subclass being referenced and not in the base class, to complete it.
The bizarre thing is that it’s being returned as the subclass. It’s only just missing the rest of the variables in the inspector, like an enum that states which stats are being affected.
Oh right, so your values are not being serialized?
Yep!
okay, first make sure your custom editor is not re initializing those values or anything like that
Do I need a custom editor? If so, which sources can you point me towards?
I thought that's what you did with the whole reflection thing?
I am trying to make a button that teleports players to an dungeon instance in ummorpg. the 'dungeons' are arenas. this is the code. I can open the panel and click the button but nothing happens. any ideas why?
Nope. Hadn’t even started on that. Thought I didn’t need it.
so how are you displaying your values in the editor? I thought that was your goal...
Just the default inspector and system.serializable for such classes.
But if I need a custom editor, I would love sources, pointers, and tutorials that would be relevant for the case.
@torn geode join the thread, this might take a while
@sly grove So if I'm understanding this correctly
I can keep hex tiles in memory with standard Vector2Int, correct?
Just when it comes time to show the map to the player, that's when fancy math needs to occur
Bit like this
This is what we've been discussing this whole time, thanks.
Is there any way to print to the console without the associated stack trace/memory overhead?
Are you trying to get an output in editor or output in a file?
Because if it’s the latter, you could probably write your own writer pretty easily
If it’s in the editor, you could probably write one just outputs in a console window
I'm trying to output to the editor. But I found a solution, I was just googling the wrong set of words
You can access that setting in the console window's dropdown
the setting affects the one in the Player settings and therefore also changes what happens when you build
so be aware of that
Why does my node not start with an initial value I set in code when I add elements to the list with the plus button?```[System.Serializable]
public class DialogNode
{
public string label;
[HideInInspector] public string id;
[TextArea(10, 10)] public string content;
public List<string> children;
public bool isRoot;
public List<Flag> requiredFlags = new List<Flag>();
public DialogNode()
{
label = "New Node";
}
}```
because label is immediately overwritten by the serializer right after your constructor runs
how do I make it not do that?
Why aren't you using a field initializer instead?
This is all sitting inside a scriptable object of Dialog.
DialogNode is a class I am using to store data.
If I don't serialize the whole class, It wont work as a member of a list in editor.
public class SO_Dialog : ScriptableObject
{
public List<DialogNode> nodes = new List<DialogNode>();
}
[System.Serializable]
public class DialogNode
{
public string label;
[HideInInspector] public string id;
[TextArea(10, 10)] public string content;
public List<string> children = new List<string>();
public bool isRoot;
public List<Flag> requiredFlags = new List<Flag>();
public DialogNode()
{
label = "New Node";
}
}```
public string label = "New Node";
Unfortunately. That also returns nothing.
reset your script
I created a new scriptable object and no change. is there a more direct way to reset?
Well, you must've done something else or Unity is just being weird
shrugs
I looked for a default value attribute, but I don't think there is one
the other thing from before always worked for me
I'll keep plugging away at it. Thank you for taking the time to help. 🙂
you could try restarting unity
Hey guys I need help, I'm making a Mobile/Pc Game called "Ultimate Hide And Seek" I need to make roles such as Hider, Seeker and Ninja, Hider is well a hider they can only hide, Same for the Seeker but he can not hide only find And now the Ninja Can hide, Go invisible for 5 seconds and stun the Seeker. I also need these to work with online multiplayer with cross platform
so you need to hire a developer? idk if we can help you here
im trying to make a status effect system and i had it as an abstract class, but i cant find any way to reference the children scripts. is there a way to do this or should i just make one big all encompassing scriptableobject script for it?
@raven jewel
if(theObject is ChildClassType)
{
((ChildClassType)theObject).CallCommand();
}
but I haven't used abstract classes so I am not sure how that plays in.
that is how I check for an objects type when there is multiple child types
https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html
Instead of adding value to field, you can use these callbacks.
Better solution is to add an Init method and call it from monobehaviour Awake whichever is holding this class
or you can use [NonSerialized] attribute for the field which you dont want Unity to override the value. But you cant see the value in inspector anymore
@coral blade i should specify that i have potion items that are scriptable objects and they cant hold abstract classes since abstract classes arent serializable. im kind of lost on how to make the potion grab the right status effect
you need to split the potion data and potion methods.
Store data of potion in Scriptable object.
Such as potion damage, heal, duration etc.
Reference that Scriptable object to an abstract monobehaviour called BasePotionBehaviour.
Then implement them logics you want accordingly.
And then inherit that class for all potion scripts you want
that is kind of the solution i was thinking of since my method wasnt working. thank you
actually would the abstract monobehaviour be necessary? i could just the code on the scriptable object itself and just take in the different variables. since scriptableobjects cant store abstracts anyway
hey, i'm looking for some advice to optimize this cell operation as much as possible
it adjusts the tiles proportionally in a circle, as you can see
now
the tiles are grid based
but the position of the operation itself is not grid based
the affected area can be at non-integer positions and sizes
and lastly, the grid is 5x1x5 per unit
public void RaiseLowerTerrainBrush(float x, float y, int amount, float diameter) {
Vector2 center = new Vector2(x, y);
Vector2 centerTile = WorldToGridLocation(center);
float halfDiameter = diameter / 2;
Vector2 corner1Tile = WorldToGridLocation(new Vector2(x - halfDiameter, y - halfDiameter)) - Vector2.one;
Vector2 corner2Tile = WorldToGridLocation(new Vector2(x + halfDiameter, y + halfDiameter)) + Vector2.one;
Vector2 size = corner2Tile - corner1Tile;
int startx = (int)corner1Tile.x;
int starty = (int)corner1Tile.y;
int tilex, tiley;
for (int i = 0; i < size.x; i++) {
tilex = startx + i;
for (int j = 0; j < size.y; j++) {
tiley = starty + j;
Vector2 worldPosition = GridToWorldLocation(tilex, tiley) + blockOffsetToMiddle;
float tileAmount = Mathf.Abs(Mathf.Clamp01(Vector2.Distance(worldPosition, center) / halfDiameter) -1);
RaiseLowerTerrainCellCorners(tilex, tiley, amount * tileAmount);
}
}
for (int i = 0; i < diameter; i++) {
tilex = startx + i;
for (int j = 0; j < diameter; j++) {
tiley = starty + j;
MatchTerrainCellCorners(tilex, tiley);
}
}
}```
so there's my code
the first part is defining the size of the affected area (which is initially in world units)
and then figuring out which tiles in the grid to operate on, in a region
and then doing the actual adjustment on each of those tiles
is there a better way?
Hi all, I'm working on an event system to process cutscenes in 2d. In this system an NPC will have a List of Events which will be processed FIFO when a trigger is fired.
For the system to work I need to be able to create and modify events in the editor, similar to how you can input a string. I thought I could do it with Polymorphism & Serialization, but this only gets me the result depicted in the screenshot NPC just has a List<SSSEvent>.
I've read some threads and watched a video on the subject, but I can't really find an example of what I want to do. Is it possible? What can I do to make Events from the editor?
Event examples & code can be found here: https://hatebin.com/fvzdjkzkmi
I guess I'm looking for a way to instantiate a ScriptableObject from the editor... And I don't think I can from reading a bit more on that. If anyone has any ideas it would be appreciated!
After a bit more research I've settled on storing events as assets. It's not the cleanest option but it works well both from a design and development perspective.
How can i hide dropdown list by script i found in documentation theres function Hide in class Dropdown by dropdown's that i created via editor dont have that class
UnityEngine.UI Dropdowns?
yeah
i Created obj dropdown fromm UI option in editor but that doesnt have class like that
You have referenced it in script as a UnityEngine.UI.Dropdown though?
Because that seems to have a Hide and Show method
I try to do that but dropdown that i created by editor dotn have class like that
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DropdownManager : MonoBehaviour
{
public Dropdown dropdown;
public void HideList()
{
dropdown.Hide();
}
}
None of those are Dropdown components
Dropdown is a component you can add to an object, and you can have it build you one if you create it through the hierarchy menu thing
But none of those are Dropdown components, so ofc they won't fit into the field
I builded it by hierarchy menu but it doesnt have it by default it's normal? to i have put it by myself?
I know they dont gona fit it but i talk about its normal to Dropdown fromm editor menu hierarchy doesnt have Dropdown script
I think you've deleted something
2021.1.22f1
😐 2019 here so maybe thats a problem
But I highly doubt it's a feature of my version, I've used them before
I don't see there being any difference in 2019
What's the exact version you're using?
2019.3.13f1
Idk then, I can use Dropdowns and they are constructed correctly in 2021.1
I have used them in 2020.3 as well
Right click any gameobject in hierarchy, click on UI/Dropdown
I've used them in 2018 and they indeed work.
If you manually add a dropdown component, you need to properly configure it. The context menu does it automatically for you.
And when dropping reference, use the new gameobject that was created under the gameobject you selected
Are you asking for general optimization ideas for performance or is your current way causing issues or forcing worrisome workarounds?
Hey, is there any way to send UnityWebRequest GET in OnApplicationPause event? It looks like my coroutine with request is not sended if pause = true. Probably because main thread is frozen while the game is suspended.
I'm not even sure what the correct term for this is, but how do people go about solving the common issue where players can grab objects while standing on them, and then use it to essentially fly?
Because the object is constantly trying to push itself up to the held position, while the player is standing on top of it.
If anyone gets what I mean
usually when you grab an object you disable basically all physics on the grabbed object
make its Rigidbody kinematic etc.
Depends a bit on the mechanic, sometimes the objects are held somewhat far away from you or the objects are big, so you still want to treat them as physics objects
In my case I do
Unless I am remembering wrong, don't kinematic rigidbodies ignore colliders on other stuff?
so you could just clip the object through the wall which would be a problem
kinematic bodies are unstoppable forces that aren't affected by forces or depenetration, yes
Yea that wouldn't work in my case because I want my held objects to be able to physically interact with other physics objects
If I could somehow make it selectively kinematic for the player that would be nice
but that doesnt really make sense I think
You can disable collisions between it and the player
I dont see how that would be possible
I was thinking about that, my next concern would be players clipping into objects after they release them
Either by changing its layer, or by using Physics.IgnoreCollision(playerCollider, grabbedItemCollider, true)
Like if you pick up a table and can just put yourself in the center of it, I can see a lot of potential issues
You can undo it after releasing
What would happen in that scenario if I were to re-add collision while being directly inside of a large object?
Maybe you could Rigidbody.SweepTest the dragging movement and skip any movement that would result the object colliding with the dragging entity
I'm trying to think of a game that has held physics objects that don't have this issue, I might go in and just experiment
maybe it will give me an idea of how they did it
Amnesia I think has it?
oh LOL
nevermind
Was fooling around on my second play through. Probably already has 100 videos before mine, but I found this on my own so w/e.
Just alternate between jumping and clicking, just like in other games.
amnesia has that exact problem
I don't know what the proper term for that is but
So that the grabbed object is affected by the depenetration impulses but not the player
Granted it looks like in this case it's purely due to jumping logic
What about logic to just check if the player is standing on top of something, and then working around that?
I just don't know how you can properly classify when a player is on something, it might depend on the object
Don't allow jumping on props that have recently been affected by dragging? 😄
Well in my project you can't even jump
but you could take a cube, and drag it on the ground, walk on top of it, and boom
were flyin
It's because there's a resting position every held object tries to interpolate to
so perhaps if I can detect if a player is on object, just dont try to go to that resting position
You can use the contact modification api to make that collisi1on not apply forces to the player, pretty sure. Or at least not upwards forces?
I'm on Unity 2021.1.20f1
21.2 at least has it documented https://docs.unity3d.com/2021.2/Documentation/ScriptReference/Physics.html
Is it that ContactModifyEvent at the bottom?
Damn there's not too much on this
oh wait that post had a writeup on google docs
Yea the easier solution was to just to a raycast from the player's feet down, if it hits the gameobject you are holding you're technically on top of that
after that it's just about altering the physics or how the object moves to its resting position
Hey guys, I'm having a very weird problem with c# and with no answers online,
I have a class, here it is:
public class Slot
{
public Button button;
public ImageGroup group;
public GameObject Object;
public int Price;
public bool InCart = false;
public Slot(GameObject o, int p, Button b)
{
Price = p;
Object = o;
button = b;
group = button.GetComponent<ImageGroup>();
}
}
When I create a list of it, and change one of the values, or add a value, everything stays the same apart from Object variable, it changes to the last things I changed anything in the list to, here's an example -
I have this code here:
list[2].Object.GetComponent<item_Pickup>().ScriptItem = item3;
Debug.Log(list[0].Object.GetComponent<item_Pickup>().ScriptItem.name + " check1");
list[1].Object.GetComponent<item_Pickup>().ScriptItem = item2;
Debug.Log(list[0].Object.GetComponent<item_Pickup>().ScriptItem.name + " check2");
list[0].Object.GetComponent<item_Pickup>().ScriptItem = item1;
Debug.Log(list[0].Object.GetComponent<item_Pickup>().ScriptItem.name + " check3");
And here's the console (In the image),
The selected comment is saying the names of the items, BlueRing being item1, GreenRing being item2 etc...
This is weird, never happened to me before and has no solution online. Any help is greatly apricated, thank you.
I read this about 3 times and still have idea what issue you're having
What are you expecting this code to print
Yay it works perfectly
I know, this is weird. So each time I change something about the list, add something to it. change something in it. Every item in the list woks at it should apart from the "Object" one (see in the class "Slot"), every item in the list changes to the one I set
I expect it to write BlueRing each time.
But it changes every time I change something else
Oh - sounds like all of the elements of your array are referring to the same object
how'd you initialize the array
var list = new List<Slot>();
right and then... how'd you populate it
this is the weird part though, this is a shop menu, where I write if(i < 3) it generates items, but the rest are powerups, but only the items have the glitch, the powerups don't. And they are the same class
Can you simplify it? It looks like these are the two places you add Slots:
list.Add(new Slot(GetItemObject(item), BasePrice, ItemSlots[i].button));```
```cs
list.Add(new Slot(powerUp.Object, BasePrice, ItemSlots[i].button));```
So my guess here is that
powerUp.Object
and/or GetItemObject(item) are always just returning the same GameObject
those are different items in the shop... the powerups and the items
it doesn't
public GameObject GetItemObject(Items_Scriptable item)
{
//Debug.Log(item.name);
GameObject obj = ItemPrefab_G;
var i = obj.GetComponent<item_Pickup>();
i.ScriptItem = item;
i.is_Gravity = true;
i.force = 0;
return obj;
}
it just creates a gameobject with those values and returns it...
That's not creating anything
That's taking an existing prefab and returning it
it is, it's changing the Item_Pickup values
sure but
every time you call GetItemObject you're literally returning the same GameObject
no
GameObject obj = ItemPrefab_G;
return obj;```
the stuff in between is almost immaterial
GameObject obj = ItemPrefab_G; var i = obj.GetComponent<item_Pickup>(); i.ScriptItem = item; i.is_Gravity = true; i.force = 0; return obj;
there is a script right
yes
I understand that
is a scriptable objecy
that holds all the info about an item.
and I set it to be an item that I get from the code
In your loop you're doing this:
list.Add(new Slot(GetItemObject(item), BasePrice, ItemSlots[i].button));```
a new slot with the Object being the GameObject returned by GetItemObject(item)
right, and item is chosen randomly
That sGameObject is always ItemPrefab_G
in here - Debug.Log(list[0].Object.GetComponent<item_Pickup>().ScriptItem.name + " check3"); the main debug, I am debugging the value I changed
So all you're doing is taking ItemPrefab_G's Item_Pickup script, pointing it at a different item, and returning ItemPreab_G
yeah
All of your slots are still pointing at ItemPrefab_G
so when you change ItemPrefab_G
all the slots see that change
but I create a copy of it
No you don't
Where are you creating a copy?
I messed that up? I never in my 3 years of preoggramming in unity ever created a copy
so how do I do that?
The way to copy a GameObject is with Instantiate
thank you so much
I'm so dumb though
do you have an idea of how I can do this though?
idk, thank you though, a lot
I'll figure it out
I'd just say that generally changing any data on a prefab is kind of an unusual and strange thing to do
I know, because of that I never considered that a problem...
I just need to change some parts of the system
Hey guys! I don't know if this question belongs here, but I would like to make a WebGL build be edge-to-edge (no whitespaces). How would I go about doing that? I am using an SDK for the game I am making and the template is not really edge to edge. I found the Better Unity WebGL template git repo but I am not sure how to adapt it for my existing styles.css file. Could someone guide me through this?
#🌐┃web as it's not really a code question
Thank you!
Can anyone give me a bit of advice debugging my overlapcapsulse?
This is my situation, the capsule should cast forward, the yellow and red gizmo wirespheres indicate the start and endpoints
but instead it appears to cast downward and returns the debug.log name of the terrain the player stands upon
the radius is only 0.2f, so nowhere near large enough to hit the terrain if the cast were being performed properly (forward)
I feel like the method info is lying to me 😩
yeah idk? i havent used overlapcapsulse but it looks like it should be working.
yeah... seems like it's broken, although that's kind of hard to believe ...
You are not using it correctly that's why
point1 The center of the sphere at the end of the capsule.
he just needs to add transform.position + dir * distance.
Cause direction * distance is getting the a vector in the right direction but it’s not in the position you want so the end position isn’t where you want it to be. You need it to start calculating for your transform.position
origin + ...
Yeah
Can u get the current frame of a playing animation as an int and save that so u can load it in a resume function.(is this possible in unity)
thanks @austere jewel 😂
you can use Animator.GetCurrentAnimatorStateInfo().normalized time to get a normalized time of the the animation (0-1, 0 being the start and 1 being the end of the animation). If you know how many frames the animation has you could use that to find the current frame with FloorToInt(frame count * normalized time)
I assume if im halfway through the animation normalized time would return 0.5f and at 3/4 way through return . 75f
Other question. Can i feed that normalized time back into the animator component
I just want to be able to resume playing the same animation at the exact spot.
https://docs.unity3d.com/ScriptReference/Animator.Play.html
There's a normalizedTime parameter that allows you to start from a point other than the beginning of the animation. If you just feed in the same value you get from the the state info struct you should start playing at the same point in the animation
blending between animations could throw a wrench in it, but it sounds like you're using sprite animations that are not blended anyway, so probably a non-issue
3d. Just trying to save and load the game
I dont use layermask or other complex stuff so i think it should work. Ofc im saving the bools and parameters so there wont be any issue on that end.
yeah... if you're mid-transition between two animations it probably would not playback the same way when you reload. You might be able to recreate the whole state of the animator, but... is it that important? Probably more effort than its worth imo.
how do I replicate adding one of these in code?
https://docs.unity3d.com/ScriptReference/Events.UnityEvent.AddListener.html this documentation on AddListener links to Events.UnityAction.Call which doesn't allow arguments in the method call
so it can't be that
because the system in the inspector does
https://docs.unity3d.com/ScriptReference/Events.UnityEventTools.html It's this Editor-Only class
Not persistent ones.
what does persistent mean in this case
AddListener can take arguments, just use a lamda
It means it's serialized in the inspector
all right
that won't be necessary i think because my use case is the item gets instantiated at runtime and then has a listener added to it
ok so something like this?
Toggle toggle = button.GetComponent<Toggle>();
toggle.onValueChanged.AddListener(() => { ToggleActivityFolder(activityFolderKey); });```
yup
it doesn't appear to be adding the listener
oh it is nvm
@austere jewel quick question
i read that the variable stored in a lambda is a reference
it becomes a closure, which is a complex thing to explain
No, though I'd watch out if you use a for loop, the index would need to be copied to a local variable before use
ohhhh okay i wondered that
if i add a value to the call instead of a reference where does it get stored?
Research closures, I'm not going to explain them
are dictionaries addressable by index?
oh hold on
so it'd be something like this potentially
if i understand correctly
because kvp is the iterator variable so i have to make a local one
it appears to work
Hi, I have a problem with Timeline.
I created a track, playable and clip custom script, the clip has a reference of gameobject in scene.
Until I make the build it works, then when building it loses the reference.
this are the scripts:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
public class TogglePhysicClip : PlayableAsset, ITimelineClipAsset
{
private TogglePhysicPlayableBehaviour template = new TogglePhysicPlayableBehaviour();
public GameObject[] phisicGameObjects;
public bool isKinematic;
public ClipCaps clipCaps
{
get { return ClipCaps.Blending; }
}
public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
{
ScriptPlayable<TogglePhysicPlayableBehaviour> playable = ScriptPlayable<TogglePhysicPlayableBehaviour>.Create(graph, template);
TogglePhysicPlayableBehaviour clone = playable.GetBehaviour();
// clone.rigidbodies = rigidbodies;
List<Rigidbody> rigidbodies = new List<Rigidbody>();
foreach (GameObject phisicGameObject in phisicGameObjects)
{
rigidbodies.AddRange(phisicGameObject.GetComponentsInChildren<Rigidbody>());
}
clone.rigidbodies = rigidbodies.ToArray();
clone.isKinematic = isKinematic;
return playable;
}
}
using System;
using UnityEngine;
using UnityEngine.Playables;
public class TogglePhysicPlayableBehaviour : PlayableBehaviour
{
public Rigidbody[] rigidbodies;
public bool isKinematic;
public override void OnGraphStart(Playable playable)
{
}
public override void OnGraphStop(Playable playable)
{
}
public override void OnBehaviourPlay(Playable playable, FrameData info)
{
if(!Application.isPlaying) return;
if (rigidbodies == null)
{
throw new NullReferenceException("Nessun rigidbody collegato, rimuovere TogglePhysicPlayable");
}
foreach (Rigidbody rigidbody in rigidbodies)
{
rigidbody.isKinematic = isKinematic;
}
}
public override void OnBehaviourPause(Playable playable, FrameData info)
{
}
public override void PrepareFrame(Playable playable, FrameData info)
{
}
}
I didn't have this problem last year on other project
reading this thread seems that array aren't supported: https://forum.unity.com/threads/exposed-reference-for-data-in-list.497503/#post-3467992
hello, I'm making a multiplayer game like CSGO, does anyone know any good example of the movement and hit detection system used in games like CSGO? client side and server side
thats one of the most advanced subjects in multiplayer networking, there most certainly are no examples (outside the source-code of those games), only articles on its theory
Hello everyone! I am working with Unity and jslib and having some issues calling the jslib functions from within c# functions. They only seem callable from within the Start() function. Is this normal behavior?
any suggestions on whats the best way to do it?
pretty much the best freely available info on the subject:
thanks ill have a look at it
Anyone know resources (videos, books, papers, blogs) about how to apply functional programming (style) to game development, specifically in Unity?
don't. it's not a good paradigm for gamedev. you can of course apply some functional api's in your code but sparingly
best is to actually learn functional programming in a purely functional education-language like Haskell or Scheme and then realize for yourself when and how to apply it to gamedev
Some people make points about how Reactive Programming is much better suited to mobile game dev. I have no experience with it, but I believe that's kind of a functional style working with streams of data etc.
some people are fools
+1
react(ive) is nice in theory but also produces heaps of unreadable code
some people are satisfied with theoretical beauty that gets dirty immediately when encountering the actual world
i'd say in gamedev you have to mix and match a lot of paradigms to be successful.. from procedural, OOP, declarative, functional... there is room for all
but no one paradigm takes you all the way
anyway, if you want to have some functional programming in unity, the easiest way is to write your code in F# and then compile it into a dll.
true
you can also start with expressions and linq in your load/init code. thats pretty functional already
exactly
F# has pretty different API idioms than C#, so it might be very awkward to make them work nicely together
not really. btw. lot's of F# is lowered to C# anyway
well ~~~about
i just mean its not as nice as it could be as if the api were to stay in an F# environment
yeah but then you can't use unity anyway
you could also extend the unity roslyn to support F# compilation natively and then inject your custom roslyn into unity. then you'd have pretty much native support
Where I'm coming from: studied Game Design and Programming at university, worked as software engineer for a year, three more years as a Game Dev, did some fun learning exercises like the Harvard computer science course, read those "classic" books like Code Complete, Programing Pearls, Uncle Bob Series, etc, but the more I learn about game programming, the more it feels like a big mess where nobody knows what they are doing and everything gets out of hand quickly. So now I'm just trying to broaden my horizon a little. Ideally with something scientific, since most of Unity is already only anecdotal and I feel like we need more reliable sources.
Or, if there was even a single example of a functional style game, that would be something to compare against. But so far, it seems like its only being used in the enterprise cloud/backend environment.
yeah. because that makes sense
yeah, in gamedev all the best practices from the "ordinary world" go out the window real quick
don't ever let yourself fall so deep
pls
or rather they come with a big asterisk
yeah which is terrible imo
but if you don't change it yourself, well, it'll always be like that
but what are you gonna do... we can't use stuff here that is aimed at fixing OOP in enterprise environments
exactly
there are plenty of other patterns, but those aren't as "neat" as uncle bob's apostles makes it seem
game code is such a complex problem there can never be a clean solution that makes it all beautiful on the inside
I found it pretty interesting to read about how NASA and e.g. Airbus are collecting actual scientific data on how their software projects are working for them. They even do stuff like implement the same software with two different teams in two technologies or processes and try to evaluate which one suits what. I can't find any such thing about game dev. AAA only crunch out their titles, but don't seem to reflect or share much other than the occasional GDC talk (I don't want to downplay these sometimes immensely valuable talks, but in the broad picture there's not much out there).
all you can have is pretty islands
the software they write is orders of magnitudes more simple... 90% of their dev time is spent on documentation, certification and compliance
meh, wouldn't say that for everything. especially when you have to write programs in like algol for processors from 2005 because high density processors of today do not withstand space
still way simpler than your average game, but considerably less buggy
i guess that's true
also nasa doesn't have to make the rocket fly in a pretty and entertaining way, it just has to not explode and reach the target.
Something that got me starting to think about other than the typical Unity style was this: https://tech.innogames.com/reactive-programming-unity-introduction/
They are a pretty successful company here in Germany, so at least I wouldn't say it's complete rubbish, also not about making things beautiful since they need to earn their money. But again, not really making an argument for purely functional styles or anything, their blog also only dips a toe into async data streams.
mad respect for people who can throw a car to mars and drive around with it for 10 years without it crashing
but it is proabably only difficult because there are no yt videos who tell you exactly how to do it
lol
well, the code seems......ok and at first glance you get what is (supposed to be) happening just by looking at it but........especially when it comes to debugging, i'd struggle more with that than a normal oop approach
anything event-based is difficult to debug... i'd avoid that in games if there is no obvious way to validate its structure
there is a beauty in procedural code.. .you can just step through it and figure out what is going on
That's my experience as well, but intellectually, I kind of understand how state and timing is much more error-prone in theory.
yes, event/concurrent stuff needs some big design patterns, even architecture to not explode
thats why functional is nice in that space... its a very strong pattern to deal with concurrency
the best 'functional' approach is probably ecs and dots. well...it's a bit different, but purely functional if you dig deeper into it. although you write it differently
its a purely procedural approach to evaluating functions
but it has nothing like the safety that FP offers
disagree
everything in dots just yields into shared state, no such thing in FP
it always operates on the values. there's no not operating
thats only part of what FP is
FP primarily has no side-effects
and dots has massive amounts of side-effects
it has only side effects
you're operating on the input only. there is no state
just because your "function" runs on a struct doesnt make it "functional"
that makes no sense
in what way
an app without state doesn't do anything
all 'state' gets written back to the components which act as pure input again in the next frame
yes, and that is NOT functional
as i said, thats only part of it, FP also encapsulates the output such that it becomes pure input for subsequent "updates"
as does dots
no it doesnt
yeah it does
*referring to ecs as dots in this context because burst / jobs / etc is also included. and relevant to actual processing. still stateless
you could
they are not
Has anyone here made an fps game?
Im pretty sure quite many have. Just ask your question so someone will help if they know the answer
How do you make it so your hands hold a gun, and change when you pick up another gun
Ex if your holding an ar then switch to a Pistole
Pistol*
So what part you dont know? Do you want to be able to pick those guns up from ground or do you always carry them and just switch between them?
Its a pretty advanced topic. There are lots of strps involved in the process to make it achievable.
To hold gun in hand, you need to parent gun to the right or left hand of the player, adjust the position correctly of the gun.
Then parent the other hand to the gun itself, so that it rotates along with gun.
Also look into unity's new animation rigging package. There are plenty of guides on it (and yes even Brackey has a video on it)
To pickup a gun, you need something like a trigger or something which will let your player know to pick a gun. Once you press the button to pick, you just need to automate the above process in code
If I wanted to add animations to a gun (reloading for example) would I have to create a gun in blender and add those animations or are there ones I can find online?
Yes you can create your own animations in blender.
You can also use mixamo to create animations for your character.
You can also retarget any animation you find online if it's a humanoid, and you have a humanoid avatar aswell
hello everyone
so i've noticed that when i do dictionary.contains(null) it always returns true
why is this?
there's no key in the dictionary that equals to null
Firstly, there's ContainsKey and ContainsValue. Don't use Contains.
Secondly, there cannot be a null key ever, so the check is meaningless.
ah i mean containsKey
i'm doing containsKey(x) and there's a possibility that x might be "" or null
it cannot be null
x can be null
it's unclear wether x is specifically null or "" but in either case no such key exists in the dictionary, yet the function is returning true
Afaik ContainsKey will throw an ArgumentNullException if you pass null to it.
So x is either not null, or is Unity's fake null.
hmm
well it's not throwing that exception so the key must be ""
in any case though ContainsKey("") appears to evaluate true, which is definitely not expected
If x is a string then it's not fake null btw, so you can scratch that from your memory 😄
here's my dictionary entries
So have you used the debugger / logged x?
🤔
this.. doesn't seem right
is there some quirk in Contains the i'm not aware of to cause this
you should foreach over the dictionary and print its keys
this is what happened
i wonder why
Omg is that why all my this references in the constructor of an Object were null but still had their serialized fields in them
In a constructor of a UnityEngine.Object Unity will not have yet deserialized the values into the fields
The data gets filled by Unity some time after that point
before Awake is called
I was also doing some unity trickery that didn't end up working so it was directly derived from UnityEngine.Object but was made using a constructor
I was trying to show editor fields for a regular class in an editor window
but I couldn't figure it out
How would I ignore collisions between two colliders until they stop overlapping? I don't want to use layers because they should still interact with other objects and if I use Physics2D.IgnoreCollision() I can't check if they overlap to undo the ignore
Nevermind, got it by using Collider2D.Distance instead
I got this error " SceneManager.SetActiveScene failed; the internal DontDestroyOnLoad scene cannot be set active.
UnityEngine.SceneManagement.SceneManager.SetActiveScene" and came across this solution(?) https://stackoverflow.com/questions/35890932/unity-game-manager-script-works-only-one-time/35891919#35891919 and it left me with some questions. Why do I need a preload scene? Why do DDOL objects work if you have a preload scene but not if you dont? The __app object is kind of confusing me, it says "You must, and can only, put your general behaviors on "_app"" what about all my other DDOL objects like a UIManager, do I put them in the preload scene and ONLY the preload scene, as a child of _app or no?
The last question is really the most important
This whole StackOverflow post is one developer's opinion. It's not gospel. You'd have to ask that person why they made those choices.
Do you have a second opinion youd like to share?
Preload scenes do help solve a certain set of problems. I can't comment on the specifics of the other things you said or what they have to do with your error.
Your error just means you tried to set the active scene to the DDOL scene, which you can't do.
I dont understand what that means
Are you saying I tried to load a scene with a DDOL?
One of your scripts called SceneManager.SetActiveScene(), passing in the DDOL scene as the parameter
This is not allowed
that's all
e.g.:
SceneManager.SetActiveScene(someDDOLGameObject.scene);```
So all DDOL objects need to be created in the same scene?
I have no idea where you're getting this from
You called SetActiveScene in a way that is not allowed.
That is all
You say "You can't load a scene with a DDOL", the only inference I can come up with is put all DDOL objects in the same scene
I didn't say that.
SetActiveScene is not the same as LoadScene
I see
So do you mean you cant set a scene as active that has a DDOL?
Im not understanding what you mean by a DDOL scene
It's impossible for a scene to have a DDOL object in it by definition
WHen you call DDOL on a GameObject, the GameObject is moved to a special scene called "DontDestroyOnLoad". It is removed from the scene it started in.
This special scene cannot be set as the active scene.
It's not
DO you have any code that calls SetActiveScene?
Does that error have a full stack trace you can share?
One sec
I actually didn't have any code that calls SetActiveScene
And the error magically dissapeared
How odd
Possibly Im gonna look around
Nope theres nothing that should've caused that
I lost the original error so idk what script caused it
How do I make if else statements?
Google it
Hey @earnest quail , this question is probably geared towards #💻┃code-beginner, but I'd second @copper summit 's suggestion. A quick Google search will provide you with many excellent resources on this violently basic concept: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements#the-if-statement Best of luck!
There's a few ways you can achieve this, but the most obvious I'd go with is:
- Make the class serialiazable (independent of Unity)
- Create a custom property-drawer for instances of that class
... this will cause any Unity object that has a reference to your plain non-Unity class to display the class data
(I use that approach often where I have classes that need to exist outside of Unity but I need to render (or even edit) inside Unity)
Also the source of a brain-meltingly nasty feature of Unity: GetComponent<x> can return both 'not null' and 'null' for the same object at the same time, within the same frame. (took a loooong time to figure that one out - it's to do with the intersection of c# method invocation and Unity's custom null check, and the scope within which Unity's custom null is evaluated. fake-null needs to die :).)
Not Unity specific, but there is a webinar tomorrow on code refactoring: https://us02web.zoom.us/webinar/register/tZEkdOyspzsvE9bD-s0iVrdyV2P37eT9ckMm
David’s Talk & What You’ll Learn
Picture this: You’re refactoring code after a long code review. Your team lead keeps repeating themselves saying, “Don’t repeat yourself!” How much do you need to refactor? Should you just write a method with a big loop? Or should you write a framework? If you’re wondering how deep the rabbit hole goes, this is...
Hello!
What is the best way to get a vertex color from a large mesh near a specific world position? Is there some shader magic or something?
What we have thought about/tried already:
- Iterate over all vertices (Didn't tried but think the performance will be really bad?)
- Raycast on a Meshcollider and read it from there on collision (tried but we don't want to use mesh colliders)
- Custom camera with custom shader looking down that writes 1 pixel into a rendertexture with a script returning the color (seems to work kind of, but looked not so promising in profiler)
@mighty ocean you could preprocess your mesh into a lookup table //in principle emulating as if it were multiple meshes
Then you'd only have the cost of iterating through all verts once and pay for a faster lookup in additional RAM
build a BVH for the mesh, find closest vertex/triangle to query point depending on your need
if mesh is too large to just brute force with SIMD or something
yeah my colleague is trying this preprocess approach atm but for me it feels a bit over-engineered for what it does in the end (detect footstep undergrounds). So I thought there must be an easier way since the information is already there.
do you have any more information than just a point? you mention raycast and rendering... but dont see how that would work with just a single query point
We have grass painted via vertex colors on a mesh and have the position where the foot touches the ground. Now we need to know is there grass painted or not based on the vertex color.
so raycast from somewhere on the leg straight down?
yes
Does anyone have experience with syncing root motion movement over network? I have a flying dragon whose animations are made with root motion in mind. The position of the dragon gets synced which is fine but on the client the dragon always seems to be stuck in the idle animation (speed 0.5f). If I set the dragon movement to the flying animation (speed 1.0f) the client will see the dragon flying twice as fast I presume?
@mighty ocean I'd preproc a lookuptable for the faces (RaycastHit gives you the hit triangleIndex) or much rather use a texture to store that info and use (RaycastHit.textureCoord2)
@mighty ocean ```csharp
Physics.Raycast(new Ray(Vector3.up, Vector3.down), out var hit);
var tris = mesh.triangles[hit.triangleIndex];
var vertexColor = mesh.colors[tris];
I think (?) this should give you a color of the first vertex in a triangle
so probably the accuracy depends on the density of the mesh, but maybe it's enough 🤷♂️
seems like you're using it for footstep sounds?
raycast will give you triangle + barycentric coordinates, so you can just interpolate vertex values if needed
So to get things straight, you have a dragon with root motion animation and you're also syncing the position for animation?
For root motion sync, you should sync the initial point where the dragon was before the root motion begins, and also the time since the root motion began from that point.
Send these 2 data once to the other side, and then in the other client, position your dragon to the same position, and then play the animation. Speed it up until you catchup with the first client
The speeding up logic to catch up with first client requires some math on your end based on the available parameters, which is the catching up speed(which you need to fix), and second is the duration for how you need to keep the speed of animation to catchup with client1. And also to compensate for the duration your client took to catchup.
I dont know of its possible to move animations directly to some Xth frame. Im not sure if theres an option for that. But if it is, you could definitely try that approach aswell
ParticleEmitter was removed 4-5 years ago
What can I use instead of ParticleEmmiter?
ParticleSystem
but sale the same
- you still have ParticleEmitter in the code and 2) you can't just swap the names and expect it to work. Read the documentation.
Come on, bro, thanks, it worked wonderfully, I'm sorry if it seemed a bit clumsy, I'm new and very young at this....
thanks for sharing! definitely gonna try to go. do you know how long that's supposed to go for? I don't see an end time on the page anywhere
You're right, there's not. But when I added the event to my calendar it's showing as 45 minutes.
oh smart. Thanks!
Fellas, how is this even possible?
Your class name and file name need to be the same for types that derive from UnityEngine.ScriptableObject or MonoBehaviour. Also, not an advanced topic, more beginner.
@hot dock ScriptableObjects (and MonoBehaviours) need to be in a script with the same name
Does unity have an option to hide editor information of a scriptable object when a bool is set?
For example if I check the edible bool, it will show foodEnergy, etc. but it will hide it if edible isn't checked
Not natively, no. You could write code to do it.
Assets like OdinInspector have that built in by adding a [ShowIf ( ... )] attribute to a variable.
There might be on in this free option:
https://github.com/dbrizov/NaughtyAttributes
I haven't used it though.
Interesting. A shame it doesn't exist in vanilla Unity, though. Anyway, thank you!
yeah there's [EnableIf("bool")]
Looks like there's a Show/Hide as well, just reading through the examples
how to make a ball move in a 2d game?
Lol
I can't remember package name for Advanced joint creation in Unity
I have a very difficult issue I am trying to solve, I have been trying to learn
and watch videos and read documentation, but extremely stuck. Here is what I need to do
Step 1 (Complete) Instantiate Object (Players can spawn unlimited amount of objects)
Step 2 (Complete) Add data to the Instantiated Object using Scriptable Object Script
Step 3 (Not Complete) Save that data in Json maybe using a List? I am currently using Json to save normal Data
Step 4 (Not Complete) On Start, Load that data back up
Step 5 (Not Complete) Instantiate the same amount of objects there were before, and
load the same data it had before from the list.
As the player can spawn an unlimited amount of objects, the data those objects hold
will all be different, so they all need to save and load that data. I am unsure on how
to do this, can anyone point me in the right direction? thanks
wdym? Add serialization to your ScriptableObject and save them in your json list?
If you're already using Json to save data, why would the dynamic objects be different?
I just dont understand what I need to do to complete these steps. For instance if I load something from a list thats a scriptable object, how do I then pull the data from the scriptable object that was saved
if it was a list of ints, its different because its just 1 variable, but a scriptable object has data within data
So, you dont understand Serialization and Deserialization?
I guess not
this should help you out: https://docs.unity3d.com/Manual/JSONSerialization.html
oh no i know this i already done this
ive already done everything with json, i can save and load data fine
you can put serializable classes in other serializable classes and serialize them via JSON
but how?
is my thinking correct in thinking that I should save scriptable objects in a list?
[Serializable]
public class ClassOne
{
private int someInt;
private List<ClassTwo> listOfOtherObjects;
}
[Serializable]
public class ClassTwo
{
}```
no scriptable objects needed
but I need more than 1 variable saved, aswell as the objects location and how many of them there are
thats why i started looking into scriptable objects
what the heck? You can put as much data in any of the two classes you want
So, no scriptable object? so do I just attach this to the gameobject?
and how would i save this in Json?
I think you should first figure out what you want to serialize, write a class or struct that has that Data and can pack & unpack from there
and please read the documentation about JSON serialization - because most/all of the things you need should be in there
yeah i got no idea
just look up a tutorial how to do save games I guess. It's not really an code-advanced topic 🤷♂️
So why can't you save the data you want to? What's different here?
how does one add arkit using PBXProject and not get linker errors?
or better yet how does one resolve linker errors in xcode as i now have the arkit in xcode but when i build i recieve _UnityARKit linker errors
Im using Oculus Integration and im wondering if you guys know how i would get realistic slapping mechnics on a charater after you slap them in VR
ive never reall worked with something like this but
yeah
I could do it with animations but I want to make it so like a bobble head type only more realistic
Good evening everyone, my name is Adrian, I am in a regional contest in my country and if I win I go to the national one. My project is an augmented reality game, but to introduce you to the games, I need to compile my project to download it for Android, but when am I going to do that? I get these errors if someone could help me I would appreciate it very much thank you for your attention
You probably can just disable ARMv7 support.
Almost all phones nowadays are ARM64
and that is done in configuration? If the answer is yes, can you tell me how please?
In player settings
Project settings -> Player
ready
I have a problem that I am going to try my best to explain.
I have a data tree of tags, each tag has an id along with a parent and a list of children. The tag tree is stored on a ScriptableObject asset (I use SerializeReference to allow circular references).
You can reference a tag in field on a components by the tag's id.
I have a TagSet class which is a collection (ICollection) of tags (tag ids).
This is where it gets tricky, I want to be able to check if a parent of a tag in a TagSet matches a specified tag.
The way I handle this currently is to have a dictionary with the key being the id of a tag and the value being an int. Every time a tag is added the id of each of it's parents is added to the dictionary if it isn't already, and the int is increased. This way when all tags that have a specific parent are removed, the dictionary entry for that parent id is also removed.
This works great, until you get to prefabs. If you use the "Revert" menu item on a tag that was added, it will either leave the count for the parents, or revert it to the count at the time it was added meaning that if you had added a second tag, the count will be wrong.
I'm not sure if this makes sense, but I am trying to figure out a workaround to this. I tried using OnAfterDeserialze, and populate the dictionary their, but that requires getting the tags and their parents from the SO which is not allowed in the serialization thread.
good evening could you help me with this good mistake please
<@&502884371011731486> Nitro scam

Ok I'm still overthinking my architecture and I'll be really thankful if anyone gave second opinion
I have this idea of managing player state with components, kinda like ecs but in oop, I guess? Like for example, I could make a component
class Sitting : IPreventMovement, IForceThirdPerson
So I can check if player has IPreventMovement in movement script and IForceThirdPerson in camera script to do sum logic but I'm not sure how to implement and if it's a scalable solution. Make a list of classes and look up when needed?
Alternatively I could just use a shit ton of bools and if statements and do something like
if (sitting | crippled | stunned | inCar | uiOpen | inCutscene) return
You get the idea, but then I'll have to modify classes every time I add a thing 😔
At this point I'm not event making a game, just thinking of fancy patterns
If you have complex interactions during states which will have separate configuration, a simple state machine is the cleanest way to handle it I think.
No not really
It's just a bunch of independent flags to determine player behaviour at this point of concept I guess
if (sitting | crippled | stunned | inCar | uiOpen | inCutscene) return
These flags to me sound like they should be states in a state machine. Then you can easily manage them.
well except sitting
nvm, some of them look like just properties
State machine sound like it's just going to complicate it, but it might be just me.
Yea
Thought it wouldn't make sense for movement component to know all these things exist. Just that there's a IPreventMovement, hence no movement will be performed 🤷♂️
You could have an object with those properties. And pass actions through that object and it will decide what actions are allowed.
Yes that's one way to do it, like a master character controller with all these properties
You'll still need to add a property and modify a get function every time you add something tho
But anything that has a flow should be part of state machine, i.e. Sitting -> standing -> running
Then you won't be able to go from running to sitting for example
I initially looked into it because I googled something something "states"
But you said it there're some that aren't really states
Yea, your flags were just mixed. Some of them should be states, some are part of properties
Do you think the list lookup would be terrible performance wise lol
And code quality wise too
Not sure what you mean about list lookup. You want to avoid using just conditions with many switches, because it will very quickly become a mess as complexity increases
if list(character effects) has IPreventMovement don't move
I guess 'effects' suits this better than 'states'
Best way to handle complexity is to separate things to relevant groups and have objects managing them.
Funny, I started with this
Like I said with flowing conditions, which go from one to another you should have state machine. For anything like health related, you would have separate "Health condition" object wich will have all those properties for ill effects, then you would just ask it on the way if your actions must be modified, by feeding action you need to do to the object.
So,
if (uiManager allows movement) and (healthManager allows movement) and (vehicleManager allows movement) move then?
So it would work like "I want to switch to run from walking" -> Checks if health objects allows, object has a flag "crippled" returns instead of running -> hobbling
With health condition example, when handling ill effects, this manager can add Crippled effect, then do the job of waiting a certain amount of time for the injury to heal, then remove Crippled effect
What about things like moving a camera? Or handling camera behaviour in general
A component can have something like IPreventCameraMovement
Camera should have its own separate thing
If you go into cinematic flag the camera as locked
A certain type of vehicle could disable camera movement, for example
That would be best related to "movement state" machine. When you go into from walking/running/crouching into -> Getting in the car animation state -> Got in the car (will check if it needs to lock the camera depending on the car)
And health properties would be modifier that each state checks
governed by own object
So everything is separated and extendable in the future.
Sorry, just don't see the benefit of splitting things so much yet. In theory component solution is easier to use, as in
A player gets in a car, a InCar effect gets added, which has IPreventMovement and IForceThirdPerson, they then open a ui, which adds some effect with IPreventLook
Movement and camera components only need a reference to character effects controller, so do things that give said effects. Would it be better to have movement component hold a reference to controller, controller hold references to vehicleController healthController and whatever, and effect givers to controllers of their type?
I guess effect component would be monolithic and separate controllers modular
Yeah you know I'm reading this over and it starts making sense
Different components handle their own thing and a master controller compresses them down to a bool
A player gets in a car, a InCar effect gets added...
This doesn't exclude state machine for movement flow.
It's something that can be managed by the current state
So I would call to character controllers CanMoveCamera and it will check current health condition, ui, and vehicle
And from a state machine you can check CanMove which also asks a bunch of components, but you also need to force the character into standing to begin with
So I am making a roll-a-ball feature and I am wondering how I am meant to get it to be like the second one, a bit like Monkeyball I assume
Right now the addforce is single inputDirection * accelSpeed and all that, but I want the addforce to somehow go along the normal
I dont know how to angle AddForce in the direction like I am imagining it
Use Cross product between the normal and.. what?
project your old AddForce (i.e. the direction you want to move in) into the plane defined by the normal, normalize the result. That is your new addForce direction parallel to the ground, orthogonal to the normal.
myNewOrthoForce = Vector3.ProjectOnPlane(oldForceDirection, normal).normalized;
(ProjectOnPlane "flattens" a vector onto a plane which normal is normal, so here you get a plane the same orientation as the ground)
Ohhh
That is super useful
I feel like a whole new world just opened on things you can do with that
Hey, I've got a weird problem. On an app, I must find a photo. So on Android, I just used a file browser, and it's just a matter of finding the file. But on IOS, apparently, all aps can only access certain files ? So basically my file browser can't find the photo. How do I say I want a particular photo to be accessible to my app? When I go on a Mac, and try to add the photo to the files associated with my app, my app doesn't appear. Is there something I must do to declare that my app wants to access files and appear on the list?
Does somebody know how i can smoothly rotate my player controllers camera towards my navmesh enemy?
Hello everyone, I need help with something that's bugging me for a couple of days now.
I have 5 different arrays, each has different amount of things in it.
What I want to do is, generate all possible permutation/combinations from these 5 arrays to generate uniques.
Every possible thing will be generated.
Usecase; I have 5 different game objects; legs, hairs, arms, body, eyes. They all have an array of possible sprites. What I'm trying to do is generate all possible combinations of characters at once and be sure nothing repeats and nothing is lacking
Oh that's easy
You do nested for loops.
And then prepare for the machine to take a moment because things like that are OnX operations
The time to execute increases exponentially with the size of the arrays and the number of arrays
with this approach you can potentially encounter some form of combinatorial explosion (aka a deck of 52 cards produces more variations than there are atoms in the universe)
Hi , can you help me with skinned mesh renderer . My question is if there is way to reduce drawcalls when using same skinned mesh and material . Im not looking for texture baked animations or Crowd animator controllers or these kind of gpu instancing .. Also ecs/havok physics i don t want to use .. I m looking for any way to merge it but maintain functionality of the gameobject so i can use ragdolls/physics and animator .
wouldnt that be inneficient?
We r talking about low end android device .. actually 70 drawcalls with low poly stickmans ahve huge impact on performance
I have fully optimized scene with basic setups
but merging meshes on runtime on the cpu every frame would certainly be less effective than just leaving it to gpu
Oh , and is there any way how to improve performance ?
the only way i can think of is by using the baked anim technique and swapping for real mesh rendererer when you need ragdoll
Oh yes that sounds good but any tips how to check for collisions ?
i have no idea what your scenario is, i would start with approximating
bounds checks, etc
Okay, good thank you
you can, theoretically, if you have the time, to implement something similar to quake1
something like - have your skeletons in the scene, do your own skinning, do that in a job, for each agent
in quake1 they used baked anims stored in an array, the game then would interpolate vertices, similar to texture baked but without the shader part
you could in theory maintain both skeletons in the scene with colliders, without skinned meshes, and bind a mesh in your own batched skinner
That's interesting i try it .. Thanks , appreciate your help.
Ah thank you very much, I'm calculating the expected outcomes for sure, right now it is around 800 only
So it will happen via a nested for loop it seems
Hey frens ✨ 👋 Anybody here using firebase realtime database for a multiplayer game with a lot of users?
I'm familiar with Mirror but with about 100 users tops per server it's not gonna cut it unfortunately. I'm also not looking for something ultra tight sync wise, more like have player's vector3 positions and sending messages accross like chat..
Wondering if someone here has experience with it or some advice? 🔮
Does anyone know of basically a push event system for Unity? Something where I can trigger an event (either in Unity or on a server) and fire off a message to all subscribed clients? I've seen firebase but I'm having some issues with it.
hello does anyone knows how I can make a game tilemap based but the Z (height) with a different angle? For example like tibia/ultima the Z is 45 degrees.
Or alternatively, how can I change the X or Y axis too?
Example: earthbound has a Y axis in 45 degrees
Or isometric, X and Y is bent and Z is straight from the ground.
Been googling hard about it lately but no success whatsoever
check out riptide https://github.com/tom-weiland/RiptideNetworking
So apparently learn.unity.com has a course on behavior trees. I didn't know about it because it doesn't show up when you search "behavior trees." But there is a beginner ai course out there. It's decent
In this project you will learn about the fundamental concepts used in the creation of Behaviour Trees. You will also take this knowledge and apply it in Unity by building a simple simulation scenario where a behaviour tree is used to define action sequences of a thief stealing a diamond from a gallery.
Random thought: do you think the game creators in the world of West World (s1) used behavior trees for their 'hosts'?
Probably a combo of BTs for stimulus and GOAP for larger goals throughout the day. 🤠🐴
some form of fuzzy logic would be more likely
Hmmm. I looked up fuzzy logic and am surprised. I've used the technique of applying randomness to BT behaviors to make more believable ai agents. I've applied what I've found in gameaipro
yeah you can mix it with bt
theres also "utility ai" which expands on this concept
find sims 3 paper, very cool stuff
Yea I implemented a utility interface and posted in this channel before. That's how I apply the randomness from that book before
Mind if you find it for me? I would appreciate! I only ask because that slide deck has an article I want to read. The sims is awesome so if you're highlighting a paper in particular I'd love to read it
its a completely different approach to solving the problem
I can't use the asset store in my projects. I work in open source and unity doesn't currently support using the asset store from a CI/CD context. I'm reverse engineering the API to be able to do it now but right now I can't 😦
I don't want to work privately because... well I want my code to help others. Game programming is very challenging. Contributing to the global ledger is important ^^
That said I'll watch the videos from that link!
i think its this one
ive read it years ago, so dont remember if its the one
ah no thats sims 1 😄
Word. Well the sims is definitely on my radar. The concept of "smart object" (object that has its own behavior tree defined) comes from the sims IIRC. I knew the name of the programmer producing the papers and looked up their talks. I still have yet to implement smart objects myself, but its on the list
youve implemented goap?
@plucky laurel yea goap is my next area to explore
I could use some help on this. I want to disable the Unity 2DShadowCaster component in a script but the issue is I don't know how to reference it because it's not a monobehavior I cant get it with the GetComponent<>().
Figured it out it was just really weird
for anyone else you have to use allll this GetComponent<UnityEngine.Experimental.Rendering.Universal.ShadowCaster2D>();
using UnityEngine.Experimental.Rendering.Universal; (UnityEngine.Rendering.Universal in latest URPs) would mean you can just refer to it normally.
You can get your IDE to add/suggest namespaces automatically
Also - it is a MonoBehaviour. Probably don't ask things in #archived-code-advanced if you're across stuff like that
Asked because I'd never come across an issue like this before my apologies
Anyone see the problem here? What I'm trying to do is send a TryCastEvent, giving listeners a chance to Invalidate() it, and then only send a CastEvent if it hasn't been. It's currently ignoring IsInvalidated(). Ping me if anyone has any insight, please.
AbilitySlot.cs:
private void TryCastAbility() {
var tryCastEvent = new TryCastEvent(Ability,actionBar.Player);
EventBus.Raise(tryCastEvent);
if (!tryCastEvent.IsInvalidated()) {
Debug.LogFormat("{0} has not been invalidated!",Ability.Name);
CastAbility(tryCastEvent.Ability);
}
}
private void CastAbility(Ability inputAbility) {
AbilityCastArgs castArgs = new AbilityCastArgs();
castArgs.CastingPlayer = actionBar.Player;
castArgs.TargetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
castArgs.AbilityScriptableObject = AbilityScriptableObject;
EventBus.Raise(new CastEvent(Ability,castArgs));
//StartCooldown();
Debug.LogFormat("Casting system should call StartCooldown()");
}
My listener event handlers, elsewhere:
private void TryCastEventHandler(ref TryCastEvent eventData) {
if (eventData.IsInvalidated()) {
string debugString = "Invalidated!";
for (int i = 0; i < eventData.Log.Count; i++) {
debugString += string.Format(", {0}.",eventData.Log[i]);
}
Debug.LogFormat(debugString);
} else {
Debug.LogFormat("TryCastEventHandler({0}) ",eventData.Ability.Name);
}
// Check if caster has enough mana to cast the spell.
if (eventData.Caster.Stats.Mana < eventData.Ability.ManaCost) {
Debug.LogFormat("Invalidating {0}", eventData.Ability.Name);
eventData.Log.Add("Not enough mana!");
eventData.Invalidate();
}
}
private void CastEventHandler(ref CastEvent eventdata) {
Debug.LogFormat("CastEventHandler({0})",eventdata.ToString());
eventdata.Ability.Cast(eventdata.CastArgs);
}
Invalidated stuff, in TryCastEvent (constructor defaults invalidated = false)
private bool invalidated;
public void Invalidate() {
// EventBus.ConsumeCurrentEvent(); // May cause errors if used, could consume wrong event (needs confirmed) probably less confusing to just do it manually anyway.
invalidated = true;
}
public bool IsInvalidated() { return invalidated; }
Output:
I'm thinking maybe it's not being Invalidated before it reaches if(!tryCastEvent.IsInvalidated()) but I don't think so. I'm pretty sure this should be fine
Stepping through it, it looks like the event handler is being called after the if statement
@unkempt nova you nailed it; exactly right. Also, this is an uh oh setup because you are fighting with your decoupled setup.
I haven't considered this deeply but do consider an alternative setup... maybe use two events instead of one for this? Or maybe this isn't a place for events given an invalidated state is defined by collaborating classes
I'm being told my eventData is being copied, twice. I think that may be it
Hmm is that so? I never considered if events were copied or a ref passed in. Sounds like the former based on what you say
I'm not sure. Person saying it may be being copied is no longer clear on the cause now
I got it rolling. I was forgetting ref and in for my calls. DERP. Thanks, comrade mudkipz
@unkempt nova no problem comrade! Don't forget-- there's a party in Kiev. Don't be late!
how do i do public class Player : GameObject?
You don't
Welcome to #archived-code-advanced. As GameObject is sealed, you can't inherit it. If you don't know what that means, pick another channel :)
can i make it to not to be sealed via c# sources of Unity?
I need Player for example to be an object, not a component
There is not prototyping reason, there is logic issue in general, i dont understand why Player is a component, while for example Mesh of the Player is real component, but not Player, Player is an object
Vertical hierarchy lost there with sealed gameobject class
Player is a GameObject, with a set name. A GameObject can have one to n components attached
I don't see what you mean
if i cant do GameObject as Player it is not true
Alright, i can show you on example what i mean
Of course you can't do that, you're comparing GameObjects to Components
Yes, thats my point, why forcing Player to be component and break logic?
Break logic?
You'll need to elaborate and provide an example as I don't see how it could break logic
With normal logic, you have weapon inherited from entity, weapon itself is and entity and not a component of some abstract gameobject
This one for example
Unity breaks this logic when anything is components of faceless nothing
You can make class that aren't components, by not deriving them from Component or its derivatives, and still be able to use them
And place in the world?
Yes
You can't place classes alone, it doesn't make sense
Yep thats why am asking
I need placeable entity with Transform component
GameObject is what i need, but i want inherit it and override some functions
So no, it's not possible. Only GameObjects can be placed in the scene, and only GameObjects can have Components attached to them.
And since you want to have a component into the scene, you need to attach it to a GameObject.
You can of course inherit from Component manually, so you have the very primitive class that can be attached to a GameObject, and provide custom implementation
Got it, thanks, any ideas why it is made so unlike in other engines?
I've never touched other engine, so I can't tell.
The only thing I do outside of unity is regular Windows Desktop apps
It's not necessarily different from other component based engines
Sure it's not like your average OOP application
(also sealed classes have a place in OOP as well)
I use vanilla C# classes all the time in my unity code. The trick is to separate responsibilities and abide by some rules.
Only game objects can be placed/instantiated in scenes. Game objects accept components, including custom scripts. In my custom scripts I write a "MonoBehaviour" class that collaborates with my vanilla c# code
I worked about 5+ years with Source Engine so that i cant inherit GameObject was like a shock for me...
u just do final class CMyEntity : public CBaseEntity and u go
I think it has something to do with unity engine actually being C++ and the code we write being C#. I think for MonoBehaviours and ScriptableObjects they are created by C++, which is why we can't get access to the constructor.
It's annoying because most good testing practices have you pass in spies/mocks into constructors
if u want custom entity like idk ReflectionProbe, u just do final class MySpecialEntity : public CEntityInstance
yep
it is true
see no reasons why just not open C++ source code?
they would not loose money on it
and plus for devs who work with C++
- to perfomance
- engine would support modules
Umm. Yea I don't know who even to ask to get an answer to this. Who is the primary brain/s of the decisions of unity as a game engine?
some guy in Unity Technology xD
Or gal