#archived-code-advanced
1 messages · Page 16 of 1
I’ve written a script that uses the jobs system to shift around the objects and camera in my scene to create a “floating origin” - what can I use to achieve the same thing in-editor via let’s say a GUI window/button?
Hello! I am making a 2d hack and slash game and I would like to have the enemy sprites to get sliced up when the sword object touches them. How can I cut a sprite during runtime into two gameObjects with their own seperate rigidbodies? I would just gib the sprites manually but I want procedural stuff.
Shaders
Generate mesh
Oh, two gameobjects, you'd want multiple meshes yeah
but with sprites that's kinda hard to render, no?
So would I make a raycast from the player and then split the hit gameObject from the hit.point and the exit point?
I don't know how to generate meshes could somebody throw me a bone?
Maybe but it’s still just cut off quad, I think It’d be easiest option
Honestly, probably a shader out there for it. Unless you wanna kick around the body parts, giving each part a rigid body and such.
You know what.. I think I'll just create a bunch of different GameObjects and just disable the sprite bit and enable the rigidbody one idk
The easiest way probably is splicing up your sprite yourself, adding a renderer for each limb. Would probably require you to animate it inside of the editor unfortunately.
Damaged limbs would detach then generate their own rigid body.
GUYS.. an Important question... I am my main scene, then I go the tutorial scene... after the tutorial is done WITHOUT ANY KIND OF ERRORS I go back to the main scene, THEN IF I ENTER THE TUTORIAL AGAIN ... I GET AN ERROR THAT A GAME OBJECT IS DESTROYED (even though it's there, and its reference hasn't been modified in anyway)... how can I solve this problem??
AND NO NONE OF THE GAME OBJECTS IN THE TUTORIAL SCENE HAS THE dontdestroyonload
What's the exact error message you're getting?
I'm trying to figure out a way to export the Scenes In Build list that shows in the Build Settings window as part of my Unitypackage.
Since the Export Package UI does not allow me to add the list to the export, I'm thinking of going down the EditorWindow API.
It appears to be possible to construct the List<EditorBuildSettingsScene> which is part of the EditorWindow.
I'm looking at the example in the Unity Documentation on page https://docs.unity3d.com/ScriptReference/EditorBuildSettings-scenes.html
but it's unclear to me as to how I can invoke this script, and see what it does.
not sure if it's what you mean but the [MenuItem("Window/Example Window")] attribute will add an option to open the window, under Window -> Example Window
Thanks. I can see that and understand how this works in the context of the example.
But how can I use this when I export the package and give it to a colleague?
Would they need to manually invoke Window -> Example Window to populate the list, or can I put it in an Awake() function? If it can be put into an Awake() function, which one should I put it in to ensure it's executed first?
If I keep it in OnGUI, but skip the window creation aspects of the example, I imagine that would do it?
OnGUI is called when the window is open, you could take the button out but it would still need the window to be open
When opening a Unity Project from the Hub, what is the 1st user accessible function that is called by Unity? (Independent of Scenes)
Or would I need to (a) put it in the Awake() function of one of my scenes, and (b) always save my project (before exporting) with that scene as the active scene?
Ah ha. Thanks. I'll have a look.
Do you think what I'm proposing would work?
Actually, I have to rephrase my earlier comment.....
What is the 1st user accessible function that is run by Unity after Import Package -> Custom Package completes?
I'm not entirely sure what you're trying to do with the scene list but I'm sure you can get something working
Thanks for taking the time.
My use case is Peer Review by students studying a course where I'm their tutor.
What the students currently do for their reviews, is to open a new empty project and import the unitypackage the other student submitted.
They then find the scene we told the students to create, load it, and then run it.
But it would be nice if this could be automated.
In our previous workshops, we've always had just one scene, so it was straight forward. But this time, there are several and the students can name them as they wish.
So I want to give the students a template script where they can list their scenes for Unity to add when the import finishes.
I found this: https://forum.unity.com/threads/how-to-run-a-setup-method-when-a-package-is-imported-updated.656470/
Maybe I can figure out a way to get it to work satisfactorily.
I don't mind if I have to give them some simple instructions on how to make it work.
@obsidian glade thanks for the links.
I was wondering why you'd watch a package that would start meddling with the scenes, but that makes sense - the Load attribute may well work as the package is imported anyway
How can I get a list of scenes in my project? (Not the just the loaded scene, but the whole collection, if I have more than one.)
Neither EditorSceneManager not SceneManager seem to be able to do this for anything but the currently loaded scene, or from the Scenes In Build list.
(Do I need to use BASH to do this?)
Yea, I've looked at those.
I looked in the Scene's associated meta file, and each scene has a GUID. Thus, Unity is aware of them. How come it's not possible to find them in the assets list? Using a query like t:scene?
AssetDatabase.FindAssets("t:Scene"); Doesn't work?
I haven't tried that statement. I'll try now.
My BuildSettings list is empty, and I'm trying to populate it automatically by scanning my project.
Yes, that's returning the right number. Cheers.
Thank you!
@obsidian glade : cheers. I think it will work.
Sorry I was out.. I'll post it in a bit
Hi, I stuck here
I want to set for each type of writable objects delegate method to write them from theirs type to byte array
Byte here in correct way must be like typeof targetType, but its incorrect way
@quartz stratus
The thing is when i am in the scene for the first time, it works right... when i am in it in the 2nd time, I WILL HAVE THE ERROR.... I thought most likely it is related to the observer pattern BUT I MADE THE SCRIPT UNSUBSCRIBE WHEN THE GAME OBJECT IS DESTROYED (which is supposed to happen when we leave the scene)...
public class NetworkWriter {
private Socket socket;
public void Write(String value) {
Write(Encoding.ASCII.GetBytes(value));
}
...
public void Write(byte[] value) {
socket.Write(value);
}
}
you can extend textstream / binarystream instead and add more types to it
you can't author a serialization framework
does that make sense?
Understood, thanks
But message sender/receiver is a big part of library, hard to rework
Can I use reflection and opcodes to create generic statics?
Or no way to implement current architecture?
In reference author used mono.cecil and updated assembly on (after) compiling
hmm
what are you trying to do?
what is the objective i mean? the big goal?
Library mirror networking
Try to rework it to dedicated server without unity
Or better to use server build?
hmm this is pretty ambitious
i am not sure how you would use the very valuable "codeweaved" (instrumented) unity components outside of unity
i can see the value generally
Question: Is there any better way to initiate value on AddComponent but before the component’s Awake is called, other than turning GameObject’s active state on/off?
Oh, thats easy, I import main unity dll with gameobject and other unity components, but they doesnt interfere
it would be better to deal with the attributes and such without codeweaving
i wouldn't try to do codeweaving
so don't Emit anything
because on the server the performance benefits will not matter for now
If I understand you correctly you can use factory (maybe with pre-setted data in repository(pattern)) or use framework like zenject. it has constructors which called (as i remember) before awake, but i'm not confident in that
What's better?
generic static class with field Action"writer"
Or static class with property writer which search for (type writer) in dictionary?
really depends how many types. ideally you just have overloaded methods
i think avoiding generics
You’d still need to call AddComponent with factory. Zenject also couldn’t figure it out and just inject after Awake for AddComponent.
in mirror what exactly is being written?
is it a whole component that gets passed in? a struct? or one of a finite number of types
i see they do my approach here - https://github.com/vis2k/Mirror/blob/master/Assets/Mirror/Runtime/NetworkWriterExtensions.cs
okay i see what they are doing now
unfortunately their architecture is really jank
you should declare a dictionary and when a key is missing for the type by name, "codeweave" on demand (i.e. use reflection to just do the serialization)
you can deal with emitting the right stuff later
where is the code that does the actual codeweaving?
so yes you would replace that Writer<T>.Write line
https://github.com/vis2k/Mirror/blob/3ec5ca758e7182d4b8195f8f636c8318012f3e81/Assets/Mirror/Editor/Weaver/Weaver.cs
Then
https://github.com/vis2k/Mirror/blob/6c1dc5255ef76f6dcc8875fba47f46348e1d537c/Assets/Mirror/Editor/Weaver/Processors/ReaderWriterProcessor.cs
Then creates generic statics
https://github.com/vis2k/Mirror/blob/b4d7b355fc00525800fd0fda998b0d4fb1a582cc/Assets/Mirror/Editor/Weaver/Readers.cs
hmm
yeah
it's hard to see if it actually uses stuff from the unity api
maybe build the assemblies in the editor, then use stubs for UnityEngine.dll
it's so jank
And I dont want to do this😁
like mirror isn't even setup as a package.json package
i have a feeling it depends a lot on subtle details of unity
yes, you manually initialize it
^ from the inspector
@jolly token alternatively, there's OnEnable which I believe is called before Awake
Awake is being called before OnEnable, in a per script basis. So It's Awake1 -> OnEnable1 -> Awake2 -> OnEnable2 and so on
but if what you want is to Instantiate the GameObject then initialize it before its Awake method gets called, you should reconsider what you put inside the Awake method
You can’t with AddComponent 😌
It’s also called on AddComponent
I’m building DI library and want generic consistent solution.
Awake is for self-initialization only.. should only have access to stuff that are already initialized from the inspector
if you want to give it an extra 'turn', only access stuff you want to be initialized inbetween on Start
you can, you just do it
add component, then initialize
oh
that changes the context entirely
yeah, you either have to go with a global containter used in awake, or make them implement some IInitializable which would take the containter, or use reflection
but either way, you'd either have to hack it with globals, or abstract away adding components
pooling
it's true inactive game objects
but you can make a facade i think
can you overload AddComponent in an extension method?
there is a dirty way to do this 🙂
where it will get from a pool
Yeah that would be fallback, but I’m researching if there is a way because it’s better to support Unity messages
How can I pool a Component and attach to exiting game object?
I don’t mind having overload or alternative API to add component
not possible
components cannot be detached. They live and die on a single GO
Hello everyone, not sure if this is the right channel to ask this: Is it possible to share a screenshot through a QR code with zxing? And does it work with WebGL?
Is anyone here familiar with the Bézier Path Creator?
which one
what about it
you cannot 😦
i think you'd be best off doing
I'm trying to add nodes to my path in script.
but every time, i have to make a new one or what?
hmm i used that tool a long time ago for a project, pretty sure it has a SetNodes or something function
ok ill look into it
I guess are you trying to calculate 0.65 or 0.5
that's inverse lerp
this is exactly what the lerp function does
I feel dumb now, I always overlooked that function, thx!
i mean you're not wrong, it's a remap function, but 0-1 is a special case
well I learned something new which is awesome
Remap is basically InverseLerp from the old range, then Lerp to the new range, but if the new range is 0-1, you're done after the InverseLerp
if you want to return 0.65, that's Lerp
Like this
well it'd be a Vector2 like (0.65, 0.65)
there is no other callback for initialization, and you can't detect component addition from the outside, as far as I'm aware
I'd add an extension method for game object called AddAndInitializeComponent that would take the di container as the first argument, and then just pass that around
or something similar
Do you know how to generate a new BezierPath in a script? The documentation shows this:
But I'm confused on how to use this method, if I have an array of vector3's, how would i go about generating a bezierpath?
Its probably like VectorPath path = new (What goes Here?)().GeneratePath(ArrayOfPoints, false);
but probably don't call it just AddComponent, that could be confusing
I think the method is not in the lib, it's given as example usage
ohhhhh
im so dumb
thanks
QUESTION how do I check if I subscribed to an even already, do i have to use a bool??
events themselves only expose operators for registering/unregistering, on the specific class with the subscribed listener, you would need to use something like a flag(like your bool) to say "hey, I've subscribed". are you trying to limit your listener to only subscribe one time, or some other reason? context is always helpful
the flag is what I meant by using a bool.. so thank you for answering!
2nd, I have an event that i need so subscribe to but will do different things depending on the team. and it might happen in the middle of the game, so I might subscribe to the event more than once
A long time ago I read somewhere that uint should be preferred over int in shaders (HLSL) for performance reasons.
Is this true?
I am searching google now and mostly finding CPU-sided info and CUDA documents saying that int is faster since it can ignore handling overflow cases, since they are undefined.
Ran into a weird issue that feels like gimbal lock but isn't today. Hoping someone here could help out:
using CMF;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraTilter : MonoBehaviour
{
[SerializeField]
private Transform center;
[SerializeField]
private Transform tiltToMatch;
[SerializeField]
public Transform looker;
float lastControllerY;
CameraController controller;
private void Start()
{
controller = FindObjectOfType<CameraController>();
lastControllerY = controller.transform.eulerAngles.y;
controller.flipCamera = false;
}
void Update()
{
//center is the fulcrum of the staff, tiltToMatch is the top of the staff that it tracks
Vector3 direction = tiltToMatch.position - center.position;
direction.Normalize();
center.up = direction;
Debug.DrawRay(center.position, center.forward * 100, Color.red);
Quaternion lookerRot = looker.transform.localRotation;
float rotateBy = controller.transform.eulerAngles.y - lastControllerY;
lookerRot *= Quaternion.AngleAxis(rotateBy, Vector3.up);
looker.transform.localRotation = lookerRot;
lastControllerY = controller.transform.eulerAngles.y;
}
}
I have this script that I use to tilt the camera in the direction of a staff that pivots around a fixed point. If this staff upside down, as it nears the center, the forwards vector of the transform spins out a bunch. If I specifically negate the "direction" vector before assigning it to center.up, the problem is fixed. Problem is, I can't just do this when the staff is upside down because if the staff is attached to a vertical wall, and you go from pointing upwards to downwards, the player's view gets flipped.
This is it without flipping the direction (so it goes straight from the fulcrum to the top of the staff), it spins out near the center.
And this is it when flipped, aka the expected behavior.
--also, I don't know if this is the correct place for this, lmk if I should change to another channel
Staff? I usually use a wand for this kind of stuff.
the intellectually honest answer is there isn't a static recommendation for these things
@undone coral thank you. I will make a synthetic test (related to my work) if I become motivated.
if i were studying performance practices i would look at hlsl shaders authored by the gpu vendors
the latest ones
and use their latest GPUs
and adopt those practices
@regal olive that might have been what I saw a long time ago
(the compiler warnings like that poster)
my google-fu is on point today
🙂 nice, thank you
wands are too short 😄
I've experienced a very similar issue to yours. But I'm only familiar in dealing with vectors and angles. The issues in the video I guess is that quick transition when passing over the plane.
that article doesn't test ampere gpus. ou can see that in turing, optimized latency is near 0 avg
imo it is probably 0 with compiler optimization turned on on ampere
so you maybe do not have to worry about this anymore on new gpus
I do remember seeing that the recent generations of Nvidia GPUs can do simultaneous integer (int/uint) and float operations, that might be another detail that helps.
How about calculating preferred rotation to keep forward rather than assigning to center.up?
GPU instancing for webgl?
you can get the invocation list and check if you delegate is there
should work
What is the best way to get all the data of a component in JSON format ?
I just want to send it to a server.
That's a bad way to go about things, for example, you won't be able to handle gameobject/component references
Hmm, currently the data I'm sending to the server includes all the game objects and their children and their children, so on etc - and just the names of the components. So I was thinking , for-example if someone makes changes in a component on the web it knows which gameobject it is - by the name and the name of its parents so that's how I'll be able to find that game object in unity I hope that makes sense .
This is the website
Hierarchy*
I just need a way to get all the data from a specific component and send it to the server.
Hey thank you for responding, I'm not sure I get your solution. Just to be sure the problem is clear, I went ahead and made a more abstracted out demo.
All 3 of them have their transform.up vectors set to the direction towards their target.
The first one just does that, but spins out if the target is below the pivot point.
The second instead gets set to the inverse of the direction, so it works well below the pivot but spins out above it.
The third is my closest solution, where it swaps to the regular direction when the target is above the pivot, and swaps to the inverse when it's below, but it isn't continuous, so it doesn't work. My ideal solution is one exactly like the third, but without that jump when the target goes above/below the pivot.
For the life of me I can't figure it out.
void Update()
{
Vector3 dir = (target.position - transform.position).normalized;
if (TrackOppositeDirection)
dir *= -1;
else if (SwitchDirection && dir.y < 0)
dir *= -1;
transform.up = dir;
}
And this is the code each is running
Nevermind, figured it out. Instead of transform.up = dir; doing
this.transform.rotation = Quaternion.FromToRotation(this.transform.up, dir) * this.transform.rotation;
Fixes it
I see.. Thank you
hi, wondering if someone could advise me on the best approach for this
i have a druid unit in my game actions this unit will have will allow them to transform into a bear or cat or whatever, how should i handle the changing of the unit model at runetime? the unit models will be read in file a supplied path from a json file
i dont think instantiating a new model would be the best way>? but its the only way i can think of
why not?
instantiating a new model might save you a lot of headache down the line.
if your bear/cat/whatever models have different animation rigs, then you would not only have to change the mesh, but also tamper with your animator's settings too. on top of that, if you want to be able to equip items (armor, accessories like hats, etc.) on any form, then you need to have separate sockets for each model your druid unit uses.
imo you reduce coding overhead by just having a prefab you can load with your desired mesh, animator, and sockets.
ofc, if your unit can change forms a lot, then performance might be an issue, so what you can do is pool the models and reuse them as needed.
I though instantiating a new model at run time would be expensive, i thought maybe some sort of pooling and enabling and disabling when neeeded
ah nice, ok im thinking about it the right way then, thank you guys as always
Hi, I'm having issues finding the right rotation/quarternion for adding meshes above other meshes :
the top ones are "fine" but i need to rotate my trees (and other stuff) according the plane. Except the planes have a 0,0,0,0 rotation, i need to find the rotation in code
Here's the code I'm using to create the trees :
public void AddSomePrefabs(List<GameObject> forestPrefabs, Transform plane)
{
Collider collider = this.GetComponent<Collider>();
int random = Random.Range(0, 5);
if (forestPrefabs.Count > 0)
{
for (int i = 0; i < random; i++)
{
int index = Random.Range(0, forestPrefabs.Count);
Vector3 randomPositionOnMesh = new Vector3(
UnityEngine.Random.Range(collider.bounds.min.x + margin, collider.bounds.max.x - margin),
collider.bounds.center.y,
UnityEngine.Random.Range(collider.bounds.min.z + margin, collider.bounds.max.z - margin)
);
GameObject prefab = Instantiate(forestPrefabs[index], randomPositionOnMesh, plane.rotation);
prefab.transform.SetParent(plane);
}
}
}
Ask in #🔀┃art-asset-workflow
you have the up vectors for all the objects (tile center - planet center) and you have Quaternion.FromToRotation
thanks, i'll look into it
I have a q. Can Time.time differ between Update and LateUpdate ?
I think unity updates the Time.time only once every frame, why not try yourself?
You can use Time.realtimeSinceStartup if you need more accurate time
Alright. Thank you for detailed video. Can you tell me what is looker, center, tiltToMatch and controller in your code? I think it might be problem that you’re using eulerAngle converted from Quaternion
I am trying it and it does not differ. The thigs is I am looking at "Someone elses code" spooky I know. And there is this really strange check, where he stores the current time in Update and if it does not match up he does a early bail in LateUpdate, but for the life of me I cant think of a scenario where this will even fire. Perhaps its to guard vs a hude lag spike ikd
That sounds weird. Even in huge lag spike, I dont think unity will update the timer between update and lateupdate.
exactly, so I'm wondering why the f did he do it in the first place
I mean its a rather complicated system involving procedural animation and motion matching so it's not like it was written by some noob
Maybe there is a chance that the object is disabled between Update and LateUpdate call and then enabled few frames later after Update so only LateUpdate would be called and the point of the check would be to make sure it is the same frame as earlier, although it would make more sense to use Time.frameCount or simply toggle a bool when disabling the object or something like that. I'm not aware of the way Unity calls Update and LateUpdate functions so I'm not even sure if this would be technically possible but that's the only thing I could imagine
Hello, is there a way to run a unity game without popping a window? For context my game needs to run and produce frames without any window being open.
Unable to parse Build/UnityBuild.framework.js.br! This can happen if build compression was enabled but web server hosting the content was misconfigured to not serve the file with HTTP Response Header "Content-Encoding: br" present. Check browser Console and Devtools Network tab to debug.```
How to fix this?
they talk about this a lot in the docs
maybe share the code
Hello, when i import a blender fbx gameobject with armature, there is no mesh filter or mesh renderer. How do i fix this? Is there a way to in blender/unity export/import with both armature and mesh
It's not a code question. Try #🔀┃art-asset-workflow
it might be easier to work in local space of the tile
you can use this package: https://docs.unity3d.com/Packages/com.unity.runtime-scene-serialization@0.6/manual/index.html
I'm trying to convert some thread-safe Java code into C# (I need to replicate some functions of a back-end java server a Unity game needs to interface with). The code in question is a synchronized hash table access. In java, it looks like this, for put, get, and remove:
public void removePerceivedPlayer(PerceivedPlayer perception)
{
perceivedPlayerMap[perception.getEntityId()]
synchronized(lock)
{
perceivedPlayerMap.Remove(string.valueOf(perception.getEntityId()));
}
}
I've created a ConcurrentDictionary to hold this data on the C# end of this, but I'm not sure how to actually synchronize it. Is it as simple as just doing concurrentDictionary[x] = y? No need for any fancy other stuff, C# just handles it? Or do I need to do something else?
object perceivedPlayerMapLock = new();
public void RemovePerceivedPlayer(PerceivedPlayer perception)
{
lock(perceivedPlayerMapLock)
{
perceivedPlayerMap.Remove(perception.getEntityId().ToString());
}
}
Okay, so, even with a ConcurrentDictionary, I still need to use the lock syntax?
Can do
uh
you can just use a regular dictionary
concurrent dictionary is not a synchronized map
Okay, so, I'll switch back to normal dict and do this lock thing instead
it is thread safe, but that doesn't mean it's correct, if that makes sense
i think if your java code uses synchronized
like if it does multiple things to a dictinoary
in a method call
you still want to use lock in your C# code
It's weird but despite the fact that I am generally bad at Java I understand java threading much better than I understand C# threading, because most of my C# is Unity code which is single threaded
So ConcurrentDictionary is concurrent but not transactional
that is correct
If you need transaction like check if it contains key A then get A
Other thread could've removed A between contains and getter for example
That case you would want to use lock
synchronized isn't transactional either
it's not atomic either
i'm not sure what the right word is
"only one block can be executing per thing used as an argument to synchronized / lock"
I think I heard ConcurrentDictionary also allocates on many operations
Hi guys, I have a question, is there a way to open up the mobile keyboard on both android and ios with some code? If not, how can i make one and let it work?
concurrentdictionary and concurrenthashmap are meant to be used for caching
thanks
it's not working... i used this code:
What are you actually trying to do? If the game has an input field where you expect the player to type something, it'll pop up the virtual keyboard automatically when it gets focus
no it doesnt, maybe its because im using webgl idk
If it doesn't do that then you can't fix it by trying to open the keyboard manually
mobile input fields work in Unity 2022 onwards
can u explain more please?
you mention webgl
it might not be a thing for webgl
since that mode was designed for a browser and a physical keyboard. so you might have to find a way to call it from js
It is, starting from Unity 2022
Doc its a 2k line monster sharing the code wont help us understand haha
hello, I have a character with animations, it has idle walk run etc animation, I want to add a weapon like a sword or a gun, but I want it to move along with the current animation, how could I achieve that?
just child it to the appropriate bone in your character's rig. This is not a code question, it's an #🏃┃animation question
aight ill ask there, I did child it to the hand bone, but it remains static not following the bone movement but rather the space position
thanks
lol
is it the matchmoving asset?
i don't think LateUpdate's Time.time is different than Update's
but i feel like the Time Illusion in unity is fluid
there is no static advice about time
im now trying it with the 2022 beta release
but i already tried it with the stable 2022 release
is there anything in particular i have to do to let this work for webgl @devout hare
Now, I'm designing a game system that allows players to I can design my own magic and I want to know if I can convert string from json or etc and use it to work in Script or not. The way we have designed it, the system will need 1 is the function of magic 2. To use this magic, I press E to use the skill and string that is in the json file in the Parameter "How Controll" to work in the script accordingly. picture
My use of language might be weird. I'm not good at it. 😢
I don't think you can do this, not in unity
like compiling and running a string
you cant compile and run a string, but you can read in data from a json string and use it
you should be able to load a dll if you're not doing an iltocpp build
still would no recommend that
like would go for a data oriented design for this
or implement something like a lua scripting engine or ironpython into your game
well, loading assemblies dynamically is good for modding
and both lua and python suck
compared to c sharp
loading assemblies is good for modding, but not the best if you want to do stuff in game
and lua sucks for making a whole game yes, but its a more simple syntax that is nice for if you game allows in game scripting of events
import process, but also if its for a mechanic and not full on modding you do not want to expose everything
it's less work for the dev, and more possibilities for the modder
yes, it is slightly harder to export-import, but with proper tooling it can be made easy
and given the fact that lua sucks, I'd go for assemblies any day of the week
you are on the start of a very long journey. you can look how spellsource and xmage do this
they are both open source
add the appropriate editor module in the hub
thanks
Probably so. I think ActiveScene changes after Awake called?
it also might make more sense to not have a condition to check scene
could just have a script in the GameOver scene that calls for things to be locked on Start
no need to check the scene name, if you know it will only invoke start if in that scene
okay it's weird, it is like resolving. I put in debug logs to print the visiblity and and the lockmode but neither of them work
or wait
it says lockmode none and and visible. true which is what I want
but it isn't looking very true
Suppose I need the following functionality:
- An array of type GameEffect that is displayed in the inspector
- Many implementations of GameEffect with their own logic and fields to be put into this array
- A way to display these fields in the editor, not requiring me to re-write the custom editor script upon adding new fields
- Preferably not using ScriptableObjects to avoid 20 CreateAssetMenu entries and clutter in the game files (I hear there might be a way around that?)
Here is what I am trying, but I can't help but feel it may be overcomplicating things:
- GameEffect is just a plain old serializable classes
- I use a custom editor and reflection to display all the fields and keep them editable
It feels like I'm almost re-inventing the wheel by writing my own editor that displays non-inherited fields, but I don't know how else to do it:
foreach (var field in gameEffect.GetType().GetFields())
{
switch (Type.GetTypeCode(field.FieldType))
{
case TypeCode.Int32:
field.SetValue(gameEffect, EditorGUILayout.IntField(field.Name, (int)field.GetValue(gameEffect)));
break;
case TypeCode.Boolean:
field.SetValue(gameEffect, EditorGUILayout.Toggle(field.Name, (bool)field.GetValue(gameEffect)));
break;
...
}
}
well for one your inspector looks neat!
for two -- you didn't reinvent the wheel, you invented rendering polymorphic lists in Unity Inspector
there is a nicer syntax for that switch as well
but if you're into this kind of stuff, you can buy the Odin Inspector asset and just keep a [OdinSerialize, ShowInInspector] List<GameEffect> gameEffects;
-- which you can populate from the inspector with plain C# objects that derive from GameEffect
you can switch directly on a base type, and have all the cases just be the wanted extending type + a var to save it into if that branhc is choosen
It's unfortunate that Unity's support for custom inspectors is pretty disappointing. I'll eventually automate my assetmenu when I get tired of editing it. Odin is nice though.
you realize Odin was build on Unity right? 😆
Unity's support for custom inspectors is excellent imo!
just yeah not as high level as it could be for a lot of stuff -- especially when it comes to serialization of non-UnityEngine.Object objects
At the very least it is a good practice exercise to make my own editors 🤷
oh you don't have to stop making editors if you use odin 😛
https://cdn.discordapp.com/attachments/789984871413448754/790251142872825856/2020-12-20_18-14-13.mp4
and this is plain Unity iirc (no Odin): https://www.youtube.com/watch?v=PRcPX7__k_4
Wow it lets you customize so much those are clean
Odin charges too much if you are in company with revenue, also serialize your object with custom logic which makes it hard to remove
alot of it is pretty easy stuff to recreate if needed per case
Yes many of them features have open source version
at work projects are long lived enough we do a lot of per project tools
but also got packages with stuff we carry project to project
@obtuse flume I wonder how hard it'd be to turn that small part with reflection & temp serializing into something reusable
... like a serializer/inspector that supports polymorphic lists 😆
also you probably don't need the types to be scriptable objects at this point (?)
Yea definitely not
so theoretically could use on any polymorphic list
yeah
you just need to add [SerializedReference] attribute to the list so unity doesn't revert the objects to their generic type when serializing
so i have a problem, when i reload my scene, my update function doesnt work in one of my scripts.. i did testing and the script is running but only the "Start" method runs not the rest any idea why?
Update won't run if the object is destroyed or disabled
my object isnt in the scene to begin with
Doesn't matter
the script spawns the objects in slowly from the top of the screen
The spawner isn't in the scene?
The spawner is
The spawner itself isn't spawning? Or it's not spawning the other objects?
its not spawning other objects
let me see
I'd guess perhaps you've set time scale to 0?
So are you doing that?
but it un pauses when you press esc
Because that will make this not work if time scale is 0
Anyway do the log thing
That's step 1
Print the timescale
Okay
lmaooo
fixed
yea it was the timescale
ty i honestly wouldve never thought of that
While not an advanced coding problem per se, I'm not a C# beginner and am in complete incomprehension of what's happening with my code. Maybe a C# master can help?
These two screenshots are taken one "step over" apart, with the actual current values being displayed.
How can Mathf.Clamp(130 + 0.004, 0, 130) result in 100.004 ?
For the record, before we step into this function, the previous value of this.internalLife was indeed 100. So it's like the actual computation is Mathf.Clamp(100 + 0.004, 0, 130).
Which doesn't make sense since at this point this.internalLife is 130 🤔
(this is a piece of code that handles life regeneration, and this issue arises when the stats of the entity change the maximum life)
I'm assuming max life was set to 100 and changed back to 130 sometime before the next step.
Any clean and easy ways to implement method composition in C#? I have a set of methods that have several steps, each of which can be fulfilled in different ways through different code. I have a set of final classes which use these methods in very specific and custom ways.
Is there any easy way to implement such methods that are composed through a set of steps, which can vary between said methods?
If this is a single hierarchy, then you'd just virtualize your methods and override them when necessary, using the Base keyword if you need previous functionalities.
Problem is that I would have to override the entire method. I wish to override only a very specific, logically united block of code in the method.
Making that block of code its own method, and overriding that, is one way to solve the problem, but that results in messy parameters, return types and also some logic inbetween these logic steps (as I'm now splitting one method, which has all types of fields & return-checks), which I'm wondering if could be removed by syntaxis with some feature of C#.
If such feature exists.
Have a delegate and process that for ambiguous morphing behaviors?
Furthermore, I would like this to be specifically by the pattern of composition, as there is another inheritance line that messes with it. Say A goes to B and C, and B goes to B1 and B2, and C goes to C1 and C2. If B2 and C2 now have similar code, I could not shorten it through inheritance, since multiple inheritance in C# does not exist. I could with composition, though (by B2 and C2 creating the same object as a "logic-executor")
Assuming you're only needing to inject some statements that needs to vary.
May you please elaborate?
I'm not experienced with delegates.
You'll probably want to look em up. It's a pretty broad topic.
Alright.
Ah, I see what they are. That would be one solution, but I don't know how different it is from making an abstract empty class for every single logic step (which consists of between 4-8 lines) of every single method (around 3 of them), then extending from those to the specific variations of behaviour in that logic step, and then making an object of the wished behaviour in the code. It is composition, but not encompassing properties or methods, but (together) concrete execution of a method, hence composition in methods.
With delegates, I would simply pass the wished delegate in the method execution.
If it's not possible to pass pre-defined delegates, this would actually make it worse, as then I would have to duplicate code.
The reason I wouldn't like the above implementation is because I would have to make 8-12 classes, as there are 2 of such composable methods, each with around 4-6 logical steps. Think of the naming as well of these classes. "methodA-StepB-ImplementationC". Or rather, something like "addItem-InitialCheck-FullCheck" (the dashes are actually underscores in this case. Discord would format stupidity if I used them)
Am I doing something terribly stupid or is this (composable methods) a legit C# design pattern?
All of this is for shortening and preventing duplicated code as much as possible, btw.
Probably want to write a mock up before attempting it. Large classes aren't usually what you should be aiming for even though the general idea of OOP is of that. Interfaces implementations are also a great way to lessen the amount of work you'd need to do implementing similar logics for different classes.
What I'm thinking is something like this:
abstract class BaseTest {
public void composableMethod(int input) {
if (!legalInput(input)) { return; }
int result = calculateResult(input)
postCalculateResult();
}
protected abstract bool legalInput(int input);
protected abstract int calculateResult(int input);
protected abstract void postCalculateResult();
}
class TestA : BaseTest {
protected override bool legalInput(int input) {
return input > 0;
}
protected override int calculateResult(int input) {
input++;
}
protected override void postCalculateResult() {
Debug.Log("Incremented input!");
}
}
class TestAAlternate : TestA {
protected override int calculateResult(int input) {
input--;
}
protected override void postCalculateResult() {
Debug.Log("Decremented input!");
}
}
Here we see a class BaseTest which sets the structure for the other classes. TestA and TestAAlternate have thus the public method composableMethod(), which can be called. This method is executed in different ways at precise steps, as shown by the extension and overriding of the certain logic steps in it, such as legalInput(), which checks the parameters, and postCalculateResult(), which can execute something after the main behaviour.
Keep in mind, in my case these methods are much bigger and more complex. In this case, you could simply write some duplicate code, but in my case, it's not feasible.
Notice how TestAAlternate doesn't need to change legalInput(), and thanks to this pattern, it simply derives from the previous implementation.
Hey everyone! I have a task - to make a level system for our game. The levels should have following features:
- Should have metadata, containing its displayed name, description, number of players and supported game modes.
- Should support streaming
- Preferably be a single file
I know how to do this by splitting the level into scene data and metadata, but is there a way to make it a single file? Metadata should be retrievable without loading the level whole.
Did anyone ever try to make something like this?
abstract class BaseTest {
public void composableMethod(int input) {
if (!legalInput(input)) { return; }
int result = calculateResult(input)
postCalculateResult();
}
protected abstract bool legalInput(int input);
protected abstract int calculateResult(int input);
protected abstract void postCalculateResult();
}
//Here are the component classes
class LegalInputChecker {
public bool execute(int input) {
return input > 0;
}
}
class InputIncrementer {
public int execute(int input) {
input++; //I know this won't work and I should use wrappers instead
}
}
class InputDecrementer {
public int execute(int input) {
input--; //I know this won't work and I should use wrappers instead
}
}
class IncrementAcknowledger {
public void execute() {
Debug.Log("Incremented input!");
}
}
class DecrementAcknowledger {
public void execute() {
Debug.Log("Decremented input!");
}
}
//Here implementations with a fully composed method through creating //behaviour objects that handle certain logic step.
class TestA : BaseTest {
protected override bool legalInput(int input) {
return new LegalInputChecker().execute(input);
}
protected override int calculateResult(int input) {
return new InputIncrementer().execute(input);
}
protected override void postCalculateResult() {
return new IncrementAcknowledger.execute();
}
}
class TestB : TestBase {
protected override bool legalInput(int input) {
return new LegalInputChecker().execute(input);
}
protected override int calculateResult(int input) {
return new InputDecrementer().execute(input);
}
protected override void postCalculateResult() {
return new DecrementAcknowledger.execute();
}
}
Here we have an implementation of my idea using component classes. This way inheritance can be cleared for something else, while no behavioural code is duplicated (the wished behaviour is accomplished by instantiating the correct component class)
Major benefit is simpler hierarchy and also it doesn't occupy inheritance of the Test classes.
Cons are worse performance due to creation of the component classes (they hold no values though, so little memory usage), and also a ton of component classes for every implementation of every logical step of every composable method.
My main question now is:
Am I doing something terribly stupid or is this (composite methods) a legit C# design pattern?
you're essentially doing a strategy pattern
a totally legit thing
read gof design patterns for some more context
to eliminate the memory usage, make them into singletons (they have no state anyway)
or use delegates if a lot of classes feel hairy
you don't need wrappers btw, pass the int by ref
or reassign the returned value
is metadata key value pairs or just a struct? wdym exactly by streaming?
a single file essentially means you are limited to a single scriptable object type or monobehavior type
A struct
other then that, you can stick your whole game in a single file, for all the compiler cares
I'm currently trying to embed scene into a scriptable object. That would probably be enough.
AssetReference?
have that as one of the fields of the metadata
are the levels known in advance?
AssetDatabase.AddObjectToAsset - i'm trying to do this.
ah no I don't think that would work with scenes
Yup. They will be created and edited in the unity editor.
or prefabs even
Hm... Ok. Metadata fields then. But I couldn't find good examples of working with the metadata fields. Could you point me at some examples?
you need a scriptable objects with an array of those structs, make that hold an AssetReference to the scene. Or get the scene by loading it by index
metadata files?
just make a scriptable object with all the info
or an object for each of the levels, if you're felling like it
I'd just stick it in an array though
I don't know what you're referring to when you say metadata files
In unity, metadata files are just guids of the asset
(most of the time)
or do you want to write to those?
I've meant .meta file. I feel, that's not what you've meant 😄
you want to store data there?
I'm pretty sure that data is only for the editor
and I've never seen people write to it
some built-in unity things do save data there
but other than that, I haven't seen it be used for anything besides ids
Well, I just don't want to clutter the editor with additional files. I wanted my level designers to be able to create a file, edit/delete/rename/copy the files and make the editor do everything else. I'll try storing the metadata in the separate scriptable object, and write a custom inspector for a scene file that will edit corresponding SO. Is it possible?
I don't think you'd be able to do a scene inspector, you could do a window that would find the so of the current scene
you make a function that takes a bunch of delegates as inputs, and then just call them in the correct order
but yeah, I've mentioned strategy already
Anyone know a way to access vertices on a Mesh when it's not read/write enabled? Tried using Mesh.AcquireReadOnlyMeshData(mesh) and accessing the NativeArray outputs but it still cries about the mesh being readonly?
This is for modded content which I can't manually enable read/write on
I can use unsafe accessor if the only way is directly accessing memory to yoink them
I am getting these errors
public static PlayerInputs inputActions = new();
private void Start()
{
SwitchActionMap(inputActions.UI);
}
public static void SwitchActionMap(InputActionMap actionMap)
{
if (actionMap.enabled) return;
inputActions.Disable();
actionMap.Enable();
}
this is my inputmanager. I have no idea what the error is complaining about....
I should note that I'm creating the input manager using [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
Invoke new() in start
Probably the static field initializer is the problem.
thx, that did it!
^^
I dont know if this is advanced or not but... how would i turn this ground check into a wall check
how do i make it so when im going to the right/up that when i go left/down it doesnt just go to speed 0 immediately
so it takes a little time to go to 0
use physics forces
May i just ask? I got this deliacte problem that, when im lifting an item up, that i have to "Hold the button to not drop", if i manage to get my raycast away from the box, it wont drop until i look at it again.
Codesnippet below
https://controlc.com/bf6c8096
if (hitInfo.transform.TryGetComponent (out objectGrabbable)) { Interactabl - bf6c8096
I want to, with the input system, be able to press my Interact-button to lift, and press it to drop it. As it is now, i have to HOLD my interact button, and whenever i release the button AND the ray is hitting the cube, it drops
this is more #💻┃code-beginner
this is more #💻┃code-beginner
you will probably get nothing but a crash
if it's not readable it's not readable
not sure how it gets into that state though
I've given up for now, not essential, just would've been a nice qol
I'm currently trying to embed scene into a scriptable object. That would probably be enough.
you've figured out how to take the two worst ideas and compound them into something so bad, it is going to be legendary on this server
this is fine
So in case you care, this was actually a bug with C# IL. I'm not exactly sure what causes it, but binding the property's result to a temporary actually fixes the variable. Here is the side-by-side IL. This is a bit nuts and I've never seen that before but... Whatever I guess
it sounds like your implementation of internalLife is buggy
what is it?
also possibly MaxLife
i think it's MaxLife that is buggy
i don't see a bug in the IL
those are just two different methods
internalLife is a float, MaxLife is a property that returns a float (and doesn't mutate internalLife)
Those aren't two different methods, basically the buggy version is:
this.internalLife = Mathf.Clamp(this.internalLife + amount, 0, this.MaxLife);
And the non-buggy version is:
var maxLife = this.MaxLife;
this.internalLife = Mathf.Clamp(this.internalLife + amount, 0, maxLife);
As you can see in the IL, the only real difference is that MaxLife is called earlier. But I'm not too versed in reading IL so there might be something else. Either way it definitely looks like a language issue (and I'm not kidding, the code above 100% fixes the issue).
well you didn't share the code for MaxLife
so that's probably it
i don't know what else to say
uh, looks like a PEBKAC issue to me. Look at your original screenshot. InternalLife is 100, MaxLife is 130, you add 0.0043566, so what is result of:
Mathf.Clamp(100 + 0.0043566, 0f, 130)? 100.0043566 is the correct output, so it all looks right to me
yeah
looks right to me
i mean there's obviously nothing wrong with the code
@ruby viper so uh, you know, i don't know why you thought there was an issue
I take it you guys never actually used a debugger, but the two screenshots are one step apart, in the order in which they're posted.
it seems like the line where internalLife shows a value of 130 in the debugger is the debugger showing an unreliable value
or the MaxLife property is modifying internalLife
well why not post the source for maxlife
there's no bug in the IL or in the code
i figure you wanna get to the bottom of this
ah, yeah, if the setter for MaxLife called AddLife before assigning the new value you'd get this
I wrote that MaxLife doesn't mutate internalLife
lol
certainly a bold move to claim a language/compiler fault with basic usage of properties and clamp
How else would you explain that the "fix" simply is to bind the value to a variable before using it? C# is such a high level language that it doesn't even make more sense.
This isn't like there are race conditions or anything considering this is running in "regular" Unity.
MaxLife is actually a method running extra code. It doesn't need to have a setter to mutate anything, and your debugger output indicates it (or something it calls/uses) is modifying the value of internalLife. The output of Mathf.Clamp is within range, so that's definitely not the issue. That leaves your MaxLife call
I'm posting the code tomorrow for sure!
that, or as Tachyon11 suggested, something unreliable in the values being retrieved by the debugger
Is it actual value of variable? Did you log it? Or you stepped out of the method and the value is not valid anymore hence the color is red.
I know you said you've given up, but the reason you can't use any of these methods is because a read only mesh isn't stored anywhere in RAM, only in GPU memory. You should be able to read the data directly from the GPU if you're using Unity 2021.2+ with the Mesh.GetVertexBuffer() method.
there is nothing wrong with the code or IL nepho posted
it is likely the user is misreading the debugger or there is a glitch in MaxLife
Is there a way to register to a SKinnedMeshRenderer material change? I have a bug in which a material is being changed by something and no where in my code that is being done so I want to put a breakpoint and see who is changing it, however I dont have idea how to observe that change
what do you mean, the material is being changed by something?
it still has material and materials (SetMaterial and SetMaterials) fields, you can set breakpoints on those
but that's probably not your issue
thx but nope that is not the issue. SkinnedMeshRenderer's materials array is being changed by some script or something
I'm tryig to figure out which is that something, problem is that I cannot create a breakpoint on the value of materials being changed so I could observe who is setting them
you can
why do you say you can't
in Rider at least i can
you can also "find usages"
well, thing is that SKinnedMeshRenderer is a class by Unity
it lets you set breakpoints in decompiled code
i do it all the time
would that be helpful?
oh really
lt me try
but
let me check something first
it might be possible
this is in the Decompiled code of a Renderer
yeah, that works nicely
@undone coral thanks!
Anyone have a good 2D top-view pathfinding algorithm? I have implemented A* for my project and its been working just fine, but they look very unrealistic and static
by unrealistic and static I mean a group of characters moving in a straight line, taking the exactly same path + they look like a single character without collision when moving all together
most internet resources are either side-view or nav mesh thing that applies to a 3d project
pathfinding is not the problem you're trying to solve. You should look into steering behaviors. You use them layered on top of a pathfinding algorithm to control the details of how characters move (ie spreading out, clumping up, queuing, etc etc) while still having the pathfinding control the overall path they take
A* probably one of the better algorithms for pathfinding I've tried, but that doesn't mean it'll have everything written for you. Formational logic is pretty tricky itself, and it's very specific to each game, so that's something that you'd want to figure out and code yourself.
what kind of game is it?
Yeah, it sounds about right
Ive implemented my version of A* to fit my game, but i need a clue to add some "randomness" that would make units spread out and take slightly different path every time
Adding a collider to each unit doesnt seem like a good idea, maybe add a random offset to the path they take?
For RTS games, I've seen some designs by grouping units by local space and calculations relative to their distances, and using final path time calculations to add some distance between each unit. But having a bunch of units idling and taking their own path regardless of those nearby does seem quite a problem.
Colliders are an easy way out though, and you do see that in games a lot
Probably too taxing if you got a lot of units
Well i dont think i want my units to collide in my game
In my game walkable "road" cells are placed and units have to walk ON it
Just like city builder games where you place roads
So i want my units to spread out, but not too much so that they dont get out of the road
So collider not the best approach
Thinking about it, random offsets might work
Yeah, seems tricky if you want it very fluid. It's just really depends how much is going to be active on your screen at once, so if you can just pool a bunch of units off screen you can maybe get away with adding temporary collider logic to those that are active.
Hey, i solved the buff system that i asked the other day, btw, thanks
Oh nice gj ;p
you can increase the cost of tiles close to units where the tiles have been selected as the path by said units. that way it would be less likely for the units to go by the same path. repeat the calculations at regular intervals
I've read this idea somewhere
Thanks
No, seriously. I need a normal Starcraft 2 style map file. Unity doesn't support that in any "normal" way. I'm left with two options: either write my own file format or trying to pull a squirrel on a fridge by making some Frankenstein monster out of unity supported entities.
Hello everyone, im trying to spawn items random, but sometimes it gets spanwed inside a wall as you can see in the screenshot can someone tell me what im doing wrong?
{
public GameObject item;
void Start()
{
int i = 0;
while (i < 4)
{
Vector3 randomSpawnPosition = new Vector3(Random.Range(-30, 30), 0.6f, Random.Range(-30, 30));
bool isItemOnGround = Physics.Raycast(randomSpawnPosition, -Vector3.up, out RaycastHit hit);
if (isItemOnGround)
{
int maxColliders = 10;
Collider[] hitColliders = new Collider[maxColliders];
int numColliders = Physics.OverlapSphereNonAlloc(randomSpawnPosition, 0.5f, hitColliders);
for (int k = 0; k < numColliders; k++)
{
bool isParentWall = hitColliders[k].transform.parent.name.Contains("Wall");
if(isParentWall)
{
Vector3 distance = item.transform.position - hitColliders[k].transform.position;
print("X: " + distance.x + " | Z:" + distance.z + " | " + hitColliders[k].name);
print(item.name + " has a distance from collider: " + distance);
print(" ");
}
}
item.name = "";
item.name = "index: " + i;
Instantiate(item, randomSpawnPosition, Quaternion.identity);
++i;
}
else
{
continue;
}
}
}
}```
You generate randomSpawnPosition
Vector3 randomSpawnPosition = new Vector3(Random.Range(-30, 30), 0.6f, Random.Range(-30, 30));
You instantiate at randomSpawnPosition
Instantiate(item, randomSpawnPosition, Quaternion.identity);
But nowhere do you modify randomSpawnPosition if it is inside a wall
yea i need help because i could find the right soulution yet
do you have an idea?
well the obvious solution is to check if randomSpawnPosition is inside a wall and if it is move it
yea i know as you can see in the code i did already, but the wall detection is not that good. So this is why i asked here if someone can help me
there is no code there that checks randomSpawnPosition
i know did you looked at my code? Is there maybe a way to get gameobjects in a certain radius? This: int numColliders = Physics.OverlapSphereNonAlloc(randomSpawnPosition, 0.5f, hitColliders); does not work fine
you are doing
Vector3 distance = item.transform.position - hitColliders[k].transform.position;
I think that should be
Vector3 distance = randomSpawnPosition - hitColliders[k].transform.position;
oh yea youre right 🙂
but even then it will not work correctly, you need to use the bounds of the wall
but it wont effect the wall detection because Physics.OverlapSphereNonAlloc(randomSpawnPosition, 0.5f, hitColliders); does not work fine.
Do you maybe know if there is a way to get gameobjects in a radius based on transform position
Use overlapsphere
The one you're using only returns an int and not the ref to the colliders
OverlapSphere will do it as long as the gameobjects have colliders
but again, think about what you are doing, you are checking centre point to centre point, you should be checking if randomSpawnPosition is inside the bounds of the found colliders
okay i got it thanks 🙂 @regal lava overlapsphere was the solution 🙂
Following up on my messages of yesterday, here is the full code leading to the weird behaviour. It doesn't fit in a single discord message so I hosted the code on github, here: https://gist.github.com/tbarusseau/709c25d7c8f35f73b5de9a3273eb0f5a
Pinging whoever might be interested in taking a look @undone coral @jolly token @gray pulsar @obsidian glade @long ivy @orchid marsh
had a brief look - it seems like you're updating the value this.MaxLife may take when you call it (or rather, the branch in how it's calculated) which could cause problems in what is displayed in the debugger
Repeating again, this has nothing to do with the debugger, considering binding the value to a variable fixes the issue. Even ignoring whatever's displayed in the debugger, the behavior can be observed in game. Yes the debugger step is omega-weird, but the exact same thing happens in-game. I repeat: the weird behavior displayed in my debugger screenshots is also observed in-game.
And btw thanks for taking a look! Sorry if I sound rude, it's just that I've been repeating the same things over and over 😆
what is this.SetLifeUnclamped(this.Life * modifier); doing?
Woops sorry, adding it to the gist right now
Updated. It just sets this.internalLife without any clamping or checks. This is to avoid possible infinite recursions.
So basically this is the part that updates this.internalLife in PostProcess, after modifying it. The value it's set at in this method is the value that's returned at the very first this.MaxLife property getter call.
I know it's a bit convoluted but it's the only way I found to have a clean and somewhat idiomatic way of handling stat calculations with an arbitrary number of modifiers
so your this.MaxLife call is indeed modifying this.internalLife?
(also there is Linq in there but let's pretend it doesn't exist)
Uh, I guess it is
I see it now 🙈
Is it causing an issue because
v updates internalLife during the Clamp
v old value v old value
this.internalLife = Mathf.Clamp(this.internalLife + amount, 0, this.MaxLife);
?
at this point I'm not entirely sure what you're trying to do - there's also a this.Life property being used
overall I think this code needs a cleanup of the properties so they aren't causing side effects like this to begin with
this.Life is just a public getter to this.internalLife
You're right, I need to clean this mess up
I think adding an explicit call to the update methods in private API would get rid of that kind of behaviours
Then your problem is method argument evaluation order
If MaxLife evaluated first then this.internalLife + amount is after modification, if other way around then this.internalLife + amount is before modification.
And in C# it’s latter, they evaluated from left to right
How do i convert a string to a component type ?
I have a string, consider this
string typeName = "Light";
I want to use this in GetComponent to get the "Light" component
of a game object
GetComponent(typeName) works
gameObject.GetComponent<> () // here I need to use the 'typeName' to refer to the light component
hm
oh
I get the type name in some json data, from a website.
we discussed this
there is a package that lets you represent the scene in JSON
you should use that package
it makes it possible to round trip
its purpose is to enable USD support in Unity
which is really stupid but that's what someone somewhere wants
Yea I'll look into it
you are undertaking something that is
really hard for you
and you are using reflection when you do not need to
using reflection has made things much harder
you still haven't really explained why you are automating the unity editor through a website @hardy nymph
Not sure if scene serialization will be relevant I want to send minimum amount of data from and to the web which is relevant , for speed. Here's an example:
Here I can edit the name, values of the components and it edits in the unity (in real time)
it sends only the relevant data, the serialized data of a component to unity
you still haven't really explained why you are automating the unity editor through a website
there is already a text format for the scene files, the .unity file is a yaml format
you could easily edit the scene file, and ask the editor to reload the scene
and it would Just Work
those text fields correspond exactly to what you are making
why are you automating the unity editor through a website?
right now your approach is doomed
I think the problem with reloading scene will be that it will reload the scripts.
Currently when the editor script is loaded it makes a socket connection. I guess I can have some kind of a check if it's possible.
that was funny wording 🤣
maybe it is doomed, I'm not very experienced in this stuff but learning with time .
it's just for some future projects, like later I might want to control the editor through a mobile phone (unity for mobile, something like that)
and for that I was thinking how can I show the scene in the phone, maybe by sending frames I guess
Anyone have any opinions on which Netcode setup is the easiest to work with?
I've got a slow-paced turn based game and I'm wondering what to use. I've seen UNet, Mirror, and the new "Netcode for GameObjects" but have yet to try any of them out
honestly for a slow paced turn-based game I would even consider non-realtime solutions
You have the luxury to rely on TCP and could use e.g. websockets
True, custom tcp server is a fit for turn based game
I could, but I don't want to be bogged down in the multiplayer code part if I can avoid it, but I guess that might be too much to ask for..
yes but why?
Like, theoretically I could just replicate the entire game state to everyone right?
for turn based games, you should probably use a pre-existing database-backed state
i believe there is something suitable in playfab, gamesparks
Ah, hm. That seems like a lot of back end for something smaller. It's a short single round game without persistency between rounds
I might be thinking of something else, but I believe that GameSparks is about to be shutdown towards the end of this month.
too bad
Is PhotonNetwork.IsConnectedAndReady a local check, or does it ping the server each time it's called?
Possibly Firebase? I built an REST API connection engine for it once.
How could I serialize some objects that are external to Unity (in property drawers)? I'd like to get some inspector-run-time insight into the data without needing to debug.
public class MissionState // external POCO
{
public string MyString;
}
public class MissionStateManager : MonoBehaviour // unity
{
public MissionState MyMissionState; // <-- I want to see MyMissionState.MyString in the inspector.
}
Easiest I can think of is wrapping every property of the POCO in a public getter but that seems tedious..
this is #💻┃code-beginner stuff but your class needs the [Serializable] attribute
Looking for someone who can help with a native plugin using android Visualizer API to fetch FFT data. I already have the data (created a Java plugin and get the data in Unity) but it seems to be not completely accurate. If someone knows a bit about this topic and can help polish the data, so that I get a nice looking frequency spectrum, I can offer 200$.
Erm... I don't have control over the MissionState class is what I'm trying to say...
If I could slap Serializable on it I would 🙂
Then you'd have to write a custom editor for your MonoBehaviour
Hm... yeah. I suppose I could do something fancy and enumerate the fields with reflection and expose them that way, but that seems complicated..
you wouldn't need reflection to write a custom editor
in any case you won't be able to save that data unless it's serializable
Hm.. How do I cast/reference the object in a custom drawer? I'd like to make a custom drawer for an object of type PlayerWorkingMissions which is a custom type, but .. this doesn't seem to be legal:
[CustomPropertyDrawer(typeof(PlayerWorkingMissions))]
public class PlayerWorkingMissionsPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.objectReferenceValue is PlayerWorkingMissions pwm) //CS8121 An expression of type 'Object' cannot be handled by a pattern of type 'PlayerWorkingMissions'.
{
}
}
}
so you're probably better off just making a parallel serializable object that you can convert to/ffrom the external one as needed
like a serializable object that simply holds a reference to the non-serializable object?
no
like a serialized object that holds the data you want to save
Unity assets and scenes can only save serialized data
if the data is not serialized, it will not be saved in the scene or the prefab or SO or whatever
hm.. I don't mind that, I'm more interested in just seeing some information at runtime without having to stop and debug
I'm assuming reading the data is half of the bargain of [Serializable] though, right?
so im using some method to instantiate an object, and in some cases i might want a component somewhere in the children of that object.
however i do this a lot so calling GetComponentInChildren() everytime will tank the performance
is there some way to only return it if its needed?
or maybe the compiler strips that so that it doesnt run when its not used? although i doubt that
i could make 2 methods, one that returns one that doesn but maybe theres a better way
#archived-code-general I'd say, but almost every one of my prefabs just has a root script on it which directly references any relevant children
It's very rare any external script should actually need to directly reference any object deep within a prefab
Having direct reference is the better way
Other than that it's just up to your logic
All interaction with the prefab is generally done through said root script as well in my setups.
im lokking for maybe a c# feature, maybe something like out parameters that are optional? im not sure
also the prefab is swapped during runtime
its all very dynamic so i cant just have references ready
I'm not sure what you're saying follows from what you're describing
just because the prefabs are swapped out at runtime doesn't mean you can't have references ready
There is method overloading or default argument... but this is starting to feel like #archived-code-general
ok i guess ill go with Func() and FuncReturn() that returns what i need
Func() is just void
I'm not really following. I thought we were talking about referencing components
seems like an XY problem now
that was never my question
im asking whether there is a way to not return something if i dont need it
in some cases i might want a component somewhere in the children of that object.
however i do this a lot so calling GetComponentInChildren() everytime will tank the performance
is there some way to only return it if its needed
Seems like you were asking how to get a component 🤔
no
Are you looking for the TryGet pattern?
you've lost me then
i have a method that returns something, however in that method it uses GetComponentInChildren() to get that thing to return
but
in most use cases of that method i dont actually need that return value
you could return an object that lazily calls GetComponentInChildren if you access that particular property
so its a bit pointless running something as expensive as that tens of times per second if i dont do anythign with it 99% of the time
hmm perhaps
I'm still not convinced it ever makes sense to be calling GetComponentInChildren anyway vs direct references and good api design
that seems a bit extra tho since it would just be a wrapper to that one thing
i instantiate a gameobject so there needs to be some way i get access to a component on it
why
Why just call GetComponentInChildren from caller
or that
to change some of the values which i sometimes might
but why do you need a component deep in the prefab?
Have a script on the root of the prefab
which handles all of that
opaquely
yea usually it is on the root but sometimes it might be a gameobject with children which each have that component
My answer is still the same
even more so in that case actually
Common use case is instantiating rows in a UI
A CharacterDetailRow for example should handle setting all the individual Text and Image coimponents inside itself
the thing that instantiates it shouldn't do anything except pass a CharacterDescription to it
yes the thing im instantiating does manage itself but rarely i might need to change some properties on it
in that one tiny rare case, (which I don't think actually exists), just do what cathei said
otherwise, never call GetComponentInChildren
If you really want something tricky... you could make hidden cache component to prefab root 😛
i suppose i can return just the gameobject
not the component#
which should be no cost
makes a little less sense but it sort of solves this without 2 methods
Does anybody know how to request an auth code for a player's account when trying to Authenticate an user with Firebase (Using Google Play Games) ?
Do you mean ID token?
Anyone have a good solution to having NavMeshAgents avoid each other?
Getting really weird interactions when applying a NavMeshObstacle to the Agents, I know they're not supposed to have both components but its the only solution I can think of right now... Disabling the NavMeshObstacle and enabling the NavMeshAgent in the same frame causes the unit to jump outside of the carved NavMesh from the Obstacle.
disable carving?
Its a turned based combat game, so the idea is once its the unit's turn then it would disable the NavMeshObstacle and activate the NavMeshAgent, but it seems that this both happens within the same frame and doesn't give enough time for the NavMesh to "heal" the carving
Thus forcing it to jump outside of its own carving
Disabling the carving doesn't work either in this scenario btw
can you just add a one frame delay between?
One frame doesn't seem to be enough
Any way to detect once a NavMesh has healed its carved out space from a NavMeshObstacle?
editor scripts have Update too
it's just trying to express the difference between what you'd see in the player versus the editor
there is only one PlayerLoop the profiler is just expressing something specific in the timeline
I've got a 'Guid' does not contain a definition for 'TryWriteBytes' but can see it in the documentation?... not sure how to go about ...?? updating the core library?
My Guid reference show ..\2019.4.39f1\Editor\Data\MonoBleedingEdge\lib\mono\4.7.1-api\mscorlib.dll
Microsoft documentation shows it in .NET 5, 6, and 7 RC 1?? does 4.x in Unity and the 4.7.1 reference mean it's running .NET 7.1?
no, .NET 5+ is not yet supported. the 4.x means .NET 4
so this is 5.x.x ? I better try to find 4.7 than and confirm/deny it's existance.. I mean.. this is a Mirror script, they use 2021, but are supposed to support 2019 LTS.. I don't get why I'm missing this method though 🤔
ty
ah I see the drop down now
and yes the method is not there 🤔
so.. I fixed an earlier problem by adding System.Memory.dll to my plugins... I wonder if I can import something like System.Runtime.InteropServices for an updated Guid struct? not used to fussing with stuff like this..
latest version on nuget didn't fix the error 😮💨
?
what is your objective
There is a line in a Mirror script I was trying to update to that wants to use Guid.TryToWrite(), but 2019 doesn't have a TryToWrite method
i would just replace it
I think I have 2021 installed, let me see if it's in there..
I don't know the severity/application of what the line/script is doing personally, could be important as is
only had 2020 installed, it doesn't have it either though
I think it's Sunday night for all of their crew, I'll wait on the problem till they're more online tomorrow (Monday noon already for me)
Umm just make an extension method will save your headache
Is the full code visible somewhere to just copy paste? That's probably what they did, installing 2021 to look... it should work off the asset store as is though so, I kinda wanna talk to them anyway
TryWriteBytes supported from .netstandard 2.1, they are supported from 2021
alright, let me try this..
What's the most in-depth resource on Unity's UI there is? I can't find much except the "guide" on Unity's website which aren't very technical. Thanks in advance.
Hello, I can't find any documentation on how unity rendering behaves in batchmode, anyone got any clue?
It doesn't
The ugui source itself is available
https://github.com/Unity-Technologies/uGUI
Why though
There's a lot of configuration in this so I doubt making it smaller is going to make it easier
A big file does not mean the code is bloated
Hi! I'm working on a little game jam game with some friends and we have this drawing system, but theres actually a problem! So one of the features we want to put into our game, is the ability to put away your drawing, rotate the player, and then put your drawing back. The player can't move, so the main problem is really rotation.
Our drawing system works by raycasting onto a "canvas" object and then at certain intervals of distance, adding the hit.point to the positions of a line renderer. Every new stroke is a new object, with a new line renderer (so that the ends of strokes dont connect) The problem with line renderers is that you can't rotate them when you're using world space. We tried using local space, but that ended up making the lines show up in a completely different spot.
My first attempt at solving this is making a list of all of the drawing objects, then making a list of arrays that contain their offset to the canvas. Then I take that list of arrays, and for each individual point, i apply the offset + the canvas position to every position in each list of linerenderer positions when i want to redisplay them. This works great (except the first point, for some reason, snaps to the position of the canvas with no offset?). However, when i try to apply rotations to the drawing, basically everything gets messed up. As you can see in the attached image, the drawing itself remains pretty much the same as it was when i put it down, but it ends up in a really weird position, it rotates really weirdly, and the first point still snaps to the canvas position. I've been throwing myself at this for like, 3 hours tonight, and this is my 2.5nd attempt this jam (attempts 1 and 1.5: i.imgur.com/JqO3Hgv.png). Can somebody help me out? Thanks :(
here's my "drawing utilities" class, which is where all of this is contained
Hii ! Im looking for someone who could help me convert the java code into unity C#.
public void onClick() {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phoneNumber));
startActivity(callIntent);
}
});
Help is much appreciated!
Not much to work off there
That could very well be C# code
Also "Unity C#" isn't a thing, it's just C#
Yeah well this gives errors when compiling.
I have seen an example online of converting something similar : https://forum.unity.com/threads/redirect-to-app-settings.461140/ [second respond]
but i havnt managed to get it working
I think the problem is the fact that it is meant for java and not c#
Not at all
what is this code supposed to do?
Im pretty sure it will work thanks to the Intent object
well there are no built-in features for calling phones in unity 😅 it seems like a lot of what this code does is based on an existing api that does a majority of the work for you
is this Intent object similar to a delegate?
So it works in an entirely different set of circumstances
Have you thought about researching "Phone a number in C#" instead
Yeah didn't find anything
What does this have to do with Unity?
I need it for my app
Very little
yeah a lot of these things are part of the android API :p
That's an idea, "Use Android API in Unity"
what do you mean?
is it possible to grab the emission pass from the gpu buffer?
in HDRP you can see if it's an AOV pass. the hdrp source code is pretty well written and you should be able to find where emission is by searching it
you can try Application.OpenURL($"tel:{phoneNumber}")
We tried using local space, but that ended up making the lines show up in a completely different spot.
did you trylineRenderer.transform.InverseTransformPointto convert a world position to a local position in the line renderer?
you should use local space.
yeah! i actually saw a stack overflow article recommending a similar thing, and i tried it! it definitely changed the transform in a meaningful, but it wasnt success and i couldnt wrap my head around how to make it work, so after trying it i went back to trying ideas i was more familiar with
what is your objective?
hmm
you wrote a lot
are you asking, how do i rotate a line renderer?
that's what it sounds like you are asking
yes. i need to rotate a line renderer around the axis of the player
the axis of the player
the player isn't an axis
i think you need to use local space for the line renderer
if you wanted to add a point to a line renderer from world space, transform it to the local space of the line renderer
yeah, so that works. i can add points in local space and the points will appear where the player turns to, but they wont rotate to face the player
wont rotate to face the player
do you mean the path's mesh is oriented the wrong direction?
that's a different problem
so
there is a setting in line renderer
Alignment
did you try experimenting with this setting?
it should be set to View
the points will appear where the player turns to
?
okay
the lines will transform to the new position of the canvas. that part is solved. the main problem is that the lines wont rotate with the canvas
p much
okay maybe let's start from the beginning
you are saying you want to be able to draw onto a rectangle naturalistically?
it should behave naturally?
as though we are in a 3d world drawing onto a page?
yes, as in, i should be able to draw onto a page, then turn my camera and the page, then have it turn along with the page
because you wrote so much, it makes it sound like there's some non-naturalistic behavior you want to achieve
then have it turn along with the page
you keep saying this
like
are you describing a bug, or some non-naturalistic behavior
My objective is to send the frames generated by unity to another process. It works in non batch mode. I'd like to know more about what batch mode does.
i am saying that i want the lines to appear as if they stick on the page
like on a real piece of paper pretty much
so a naturalistic drawing
ya
there's nothing unnatural about the behavior
they do this if i dont rotate the camera
you are describing
yaya
okay
well did you try setting the alignment to view?
otherwise, you can set it to Transform Z
and make sure the transform of the line renderer is pointing straight up
then it will just work
hmm okay, let me try that and report back to you
what is the application?
oh its already set to view lol
batchmode skips a player loop entry that renders all your cameras by default.
if you want to render a camera you can do something
The application is playing the game in a browser page. I send the frames over a websocket and display them in a canvas.
Why not?
Thanks I didnt know about LateUpdate
why does the application have to be batchmode?
i think this is going to be incomprehensibly hard for you
Because no window has to be opened whatsover
why exactly
what is your game?
or what is the goal?
the bigger goal
The goal is that the user will ultimately only play in the browser (we have our reasons)
the answer is complicated, but the brief reason is the performance is too poor
it isn't practical to try to develop this yourself
in batchmode?
in any mode
it works fine without batchmode
hmm
its not 60 fps but its close
hmm
well listen i make a unity streaming backend
i probably know more about this than anyone else
we dont need 60 fps so
no, it's not even going to work with 10fps
it works at nearly 50
it will barely work at all
hmm
i don't think you know what's going on yet is the thing
it's up to you
do you want to learn more or do you want to argue with me
I want to learn more, I wanna know if batchmode will work
well what is the big picture?
like what are you really trying to do? what is the game / the product?
hmm it's online shopping, metashops
okay
here is a demo of how my technology works - https://player.appmana.com/watch/bonneville
i think you are very far from getting to that goal
which is okay
is it essential that you write all of this yourself?
you should set it to transform z, and parent the line renderer to the canvas page
then set transform z to be pointing out of the page
then use local space for the line renderer
hope that helps
so this is pretty much what happens with transform Z alignment(top) and view alignment(bottom)
p sure that these relate to the alignment of the material of each segment of line rather than the actual position of the line
i think you are doing a lot of stuff sort of wrong
it is really hard to tell
i think your raycasts are funky too
and you have a lot of code going on
yeah essentially, I just used unity render streaming for the input part, but I may drop it in the future
I'll watch your demo thank you
how many years do you have to work on this?
i mean the drawings are offset to the canvas correctly, if they were to rotate in place to be flush with the paper, they would be fine
i think you're conceiving of this as mashing up a lot of open source software, and i'm cautioning you that this is really hard
consider this: you weren't aware of LateUpdate
Is there an asset to get feedback from the user and upload it as an issue to a private repository?
crashalytics can do this i think
Ima look it up, cause idk if my searching skills are getting worse by day, but can't find stuff these past few days
i also googled "unity report bug from in game post to github"
and found a bunch of results
a month I guess
I'll try LateUpdate
no, I'm a web developer, I just started a new job in game development
why does it all have to be written by you?
I looked for 'unity feedback create git issue' lol
are you sure you can't use another service?
lol
yeah i found like instabug and other stuff
i think back in the day i used crashalytics 🙂
I don't know, we found nothing doing what we needed, and I thought it wasn't that hard to do myself, so I did it
okay well it's really crazy hard
i understand you have some stuff in front of you that makes it look like it's easy
it works though, it's just that damn batchmode that isn't working as I guessed it would
it won't work period
why not?
well in order to get it to work, you're going to need a year or two of time
not one month
but it works rn
it really depends what you need to have working in a month
a demo for someone? a working website for many people?
yeah a working website, in 2 weeks
how do you plan to run your copies of a unity player?
wym?
well
do you guys have a budget?
like how much money can you spend running the thing that is rendering the items in the web shop
yeah a bit
how much is a bit?
well, sorry but I cannot give too many details, I already said too much probably
yes, but i know so much about this
surely you see that it's high yield to help me understand
my original question was about getting documentation on batchmode
you're not going to be able to start the game correctly in batchmode
because you don't know enough about all this stuff
and there is no documentation
because nobody does this
except like me
why?
okay well i think you should ask for more time
you should probably ask for 6 months
if you made a promise for 2 weeks, i mean, maybe you are working for the kind of shop that just delivers something incomplete
i don't know
that's not my question
it's hard to say
because you don't know enough about the internals of unity to make it work
what do you mean why?
yeah but it seems you do
why do you think the game wouldn't run correctly on batchmode?
okay
did you try what i said
i don't think the thing i authored can help you but i think you'll figure it all out 🙂
wym what thing
i really think you should ask for more time