#archived-code-advanced
1 messages · Page 35 of 1
what if i have a custom class with a name property? that should still work right?
You could also try using coroutines and spread the calculation over many frames?
might make the game feel more responsive
yeah
i tried, it still looks pretty laggy, and if i spread it out over too many frames then the wait just becomes way too long
Unitask is a popular solution as well, can make stuff run off main thread easier (has the same function restrictions)
// Multithreading, run on ThreadPool under this code
await UniTask.SwitchToThreadPool();
/* work on ThreadPool */
// return to MainThread(same as `ObserveOnMainThread` in UniRx)
await UniTask.SwitchToMainThread();
whats the benefit of using these as opposed to the job system though? and what do you mean not changing any info on the mainthread until it is done? i still want the player to be able to do stuff during it
The job system without using Unity's ECS solution is basically good for only doing math computations off the mainthread
You can't send in classes only unmanaged data like structs
So just like the other ways you can't use Unity Engine functions from classes inside the job
You really do need to look into the deep profiler again
There's probably a lot of stuff you can optimise first
where are the functions in the profiler? i only see general stuff like how many milliseconds are spent each frame on ui and cpu and stuff.
does it look like this?
Or this?
If you are on hierarchy view then you just click on the frame you want at the top and then can expand the stuff
If you are on timeline view then you get the graphical looking one built like an upside down pyramid
In deep profile mode you should get more layers and see what is exactly costing the most
I'm going off this page since i dont have Unity open rn
ok thanks! I'll see what i can find out about my methods' performance
What is your way to handle it?
In my voxel game, I want to add sloped and curved surfaces if voxels are placed in specific manner.
For example, the first voxel, forward, the second right and then right-up.
forward, backward, left, right, forward-up, forward-down,left-up,left-down,...
I have encoded them.
Now, the input is a path (sequence of voxel places) and I want to instantiate the correct prefabs after deconding them.
My approach is to create a tree and its labels are prefab ids e.g.. Just, traverse the tree and if the current node is a label, instantiate the corresponding prefab and then go on from the root again.
Another way is to create a hash table/dictionary. The key is code and the value is prefab id.
Do you know any better way?
that sounds close to 2d tile rule matching so maybe it's worth looking at how that's done
Hello, is there a way I can have a script update even when the game isn't running? I have a script that adjusts a UI's position relative to a parent character that I'd like to be running when I'm moving characters around in edit more.
Yes look into editor scripting
specifically you need
https://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
yo, uh i got a problem with Photon Fusion, I was watching this tutorial right there : https://www.youtube.com/watch?v=hqIZCoLHOig&t=156s and as you can see, he is using a "NetworkPlayer.Local" method, and I don't have it, someone know fou why ?
In this tutorial series I'll show you how to create an online multiplayer first person shooter with Unity and Photon Fusion from scratch. Download complete Unity project 👇
https://www.patreon.com/posts/multiplayer-fps-65725126
📍 Support us on Patreon to help us make more videos like this one https://www.patreon.com/prettyflygames
In this episo...
Is there no way to get the Laptop's Trackpad horizontal/vertical/touches in Unity ?
Hello! I hope I am right here. I need some advice please.
Id like for the players to choose an item from a dropdown list. But whatever they chose needs to have store a corresponding function. My ideas so far was to use an enum for them to pick from, and a switch case that takes their chosen item to execute the corresponding function. It is quite repetitive. Are there any better ways to approach this?
Hey, happy Christmas.
I currently work with the NavMeshAgent and some collider.
My problem is, that the Agent suddenly teleports away when it collide with a collider. I use the Set destination Method, so I have no idea what the problem is.
I am playing a game in which I can create my own spells. I, as a player, want to be able to choose from a dropdown list what effect my spell should have. Then I am done with creating the spell. When I cast the spell, I expect it to have the chosen effect on the target.
The spells effect needs to have a few bits of information: the string that is displayed in the dropdown "Heal the target by ..." , the actual information about which effect is meant , likely an enum, and the function that belongs to it to cast the spell. Maybe a data table?
But the main part that I am concerned about is how to store the function, access it easily
thank you very much, I will read that!
I see. Thank you for the quick input :> appreciated
Its a cool method for understanding the problem, definitely
I have a csharp question:
Why use the T? x = getSomething()... if (x.HasValue) { if you can do T x = getSomething.... if (x != null) { Are the 2 interchangeable?
if T is a value type then you cannot test for null because it never will be so T? is the only alternative
.HasValue and != null are same thing for nullable value types
For non-nullable value types it is not possible to assign null and != null always true
Save for native types, when I'm writing my own stuff, can you give me a good rule of thumb on when to use a Struct vs a Class for a "data type"? I feel like there's no real advantage to using a Struct (I can only think of space maybe, but then my almost-empty unity project ends up being a >50mb app on android...)
Using struct can minimize GC. Using struct or class is not relevant to your build size.
How do I make a generic method have the same parameters as the T type's constructor?
You can't. I would perhaps try a different code structure, like something that uses Func to perform the same work.
Here's what I'm trying to do at the moment, do you think I need to do it with func?
I'm trying to accomplish creating a method like inew<T> which will have its parameters automatically changed to match those of T's constructor's.
Than you can use another similar method which instead of creating objects of said type has properties corresponding to each of the parameters T type's constructor contains. Then you can use method Decorate on this property to create a decorator for one of the parameters. Gonna be something like ReadType<Car>().MoverProperty.DecorateWith( (x) => new MoverDecorator(x, ..., ...)).
As a result when you do inew<Car>(new SimpleMover(), windowColor) the Car you get as its mover has such an object - new MoverDecorator(new SimpleMover(), ..., ...).
Sorry, I can't really follow what the need for this is, there's a lot of abstraction going on, I don't even know what a decorator is in this context
It's a pattern actually
ive got basic modding support in my game using external code compiling and execution
and i need to know
if a player accesses an existing prefab and changes something on it, is that change then permanent? (in a build of course)
basically are prefab assets sandboxed in unity builds?
No
so not like in the unity editor? thats what I was hoping for
Hello guys!
I have a question for those of you who are experienced in creating architecture for the backend part of the UI.
I have several UI pages in my app, each of which collects some information from the user.
The information collected from the page_0 goes to page_1 and eventually all information has to be passed to another scene. Refer to the screenshot for the structure of my gameObjects (each representing a separate UI page)
What is the best architecture I can come up with in order to write as less code as possible, be clean and efficient?
Thanks for your time!
Editor only code, I need to iterate all my scenes, how do I check if it is already loaded? I need this check because if it hasn't been loaded, it will be unloaded when operation completes. If it has already been loaded, then it will not be unloaded.
Can someone help me?
does your agent have a rigidbody? if so, make sure its kinematic and doesn't have gravity
Yes it does.
This should solve the Problem?
I will try it later.
Thanks!
I'm looking for a way to combine OOP UI and ECS Game Model
But I can't quite figure, what pattern to use to achieve it
While UI logic can work fine with other UI logic
when it comes to ECS logic to interact with UI, I got stuck
Is there maybe any existing solutions to this, or anyone has any idea that might be useful?
Key constraint here:
Game Model is not supposed to interact directly with UI logic. It can only read/modify data, that is global (meaning can be read or modified by UI logic too)
My initial idea here: use some sort of simplified HTTP get requests, but I'm not sure if that's the way
Helloo! Is there a way to make an enumerator of all public enum types?
I have three public enums and Id like to have one dropdown list to pick which enum to use
Like if you want an enumerator for all the possible values of an Enum type? You can just do var allValues = (MyEnum[])Enum.GetValues(typeof(MyEnum));
thank you but tats not what I meant ^^ Let me phrase it differently
As a game developer I would like to offer a drop down menu in the editor. That dropdown menu should display the choice between several existing enum types. For example "objects", "people", "locations".
I have decided to do a little hack by creating another enum that fills this dropdown. Depending on that I do a switch case
You can do it with reflection, by calling GetTypes on your assembly and iterate all types defined. However it is better to have separate list for it for future management and refactoring.
Ah interesting! I will remember i for the future, thanks!
The Unity 2022.2 patchnotes include:
Scripting: Allowed you to pass additional files to the roslyn analyzer and make them part of the dependency graph.
Does anyone here know what that means exactly? I cannot find any further details via Google or the official docs 😅
I'm especially confused since I managed to pass additional files in 2022.1 already with acsc.rspfile
The second part is probably the important part, maybe it means additional files will now be properly tracked and rerun analyzer/SG when they change.
Currently you can pass additional files, but changes won't be picked up because Unity is not aware.
what's the official way to pass additional files in unity? adding a csc.rsp file seems like a hacky solution, but it worked
Not sure if there's an official way, but I personally just add it via additional compiler arguments.
That does make some sense, thanks!
I'm not sure though, just interpreting what it says, but yes that's currently one of the big pain points of using additional files with analyzer/SG so it's hopefully to address that problem.
My biggest pain point is that diagnostics aren't displayed in IDEs for some reason 
Hi all. I have a bit of code architecture dilemma
This is actually from Fusion BR sample, but the case is general:
There's a class called NetworkGame(NG) that handles player connecting, waits some initialization from each player, and then passes to Gameplay(GP) for it to spawn the actual player character
I wanna add some login and character select, which would fit in NG, but login and chara select only happens on certain game mode, whether the session is official, etc
So i'm thinking of moving the Login and CharaSelect sections to another class. Altho these are still very tightly coupled with NG. My justification to "split" them is just bcoz Login and CharaSelect is not a code flow that always happens
Is there any way to create a persistent TransformAccessArray? I want to have my units run a boid simulation I feel that being able to Add onto my existing list rather than have to re-create the list every frame would be a huge boost to performance
using Unity.Collections;
using Unity.Entities;
using Unity.Transforms;
public class MySystem : ComponentSystem
{
private NativeArray<Transform> _transforms;
private TransformAccessArray _transformAccessArray;
protected override void OnCreate()
{
// Create the native array with the desired length
_transforms = new NativeArray<Transform>(100, Allocator.Persistent);
// Create the TransformAccessArray using the native array
_transformAccessArray = new TransformAccessArray(_transforms);
}
protected override void OnDestroy()
{
// Dispose of the native array when the system is destroyed
_transforms.Dispose();
}
protected override void OnUpdate()
{
// Use the TransformAccessArray as you would normally
// ...
}
}
@thin wagon By creating the NativeArray with the Allocator.Persistent flag, you can ensure that the native array will not be garbage collected and will remain in memory until it is explicitly disposed of. This allows you to reuse the TransformAccessArray and avoid the overhead of re-creating it every frame.
is there no way within the editor to modify the properties of added Scenes' PhysicsScenes?
Hi. A question about using unity as library in a native Android app. I was able to make it work with a barebones unity app that does nothing, but once I added a 3rd party plugin to my unity app, I get an error when I try to build the native app: "Could not find :poseplugin:. Required by: project :app > project :unityLibrary"
Now, what should I do? Im very new to native android development, so im not sure if I should add the 3rd party library somehow to the native app or what
I checked that the .aar file of the plugin in question (posePlugin) is present at the unityLibrary\libs folder in the project that unity created
and the build.gradle of the android project created by unity looks like this: https://hastebin.com/xujimemeno.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
on line 6 it lists the poseplugin
so somehow android studio is not able to find it, although the file is present in the libs folder
Changing a camera's orthographic size rebuilds the entirety of my Screen Space Camera canvases and it lags a lot. Is there any way to fix that? I cannot use overlay canvases!
I'm making instances of classes using constructors and calling them with the proper parameters using Activator.CreateInstance(),
however, some child classes don't have the same parameters and instead pass default values to the parent constructor.
For example:
public class Foo
{
public Foo(string v) { }
}
public class Bar : Foo
{
public Bar() : base("defaultValue") { }
}```
Using Activator.CreateInstance() on this child class with the parent parameters results in an error as the parameters don't match.
Is there a way to selectively use parameters to fit the constructor? So you would pass a string and if you generate a Foo instance it uses that string, but if you generate a Bar class it drops the string to fit the constructor.
I could also make a second constructor with all parameters and just don't pass them to the parent constructor but if there is an easier way that I only have to implement once that'd be great.
You can have different constructors with different parameters. Just make another constructor with nothing as a parameter. Is that what you’re looking for?
for the parent class then? i do actually need those parameters there, so I'd rather pass all possible parameters and have it dynamically drop some of them based on the available constructors
I’m not quite sure sorry. I’m sure there is but I don’t know it.
I guess you could always pass in null values into a constructor and filter those out but I’m not quite sure what you’re trying to accomplish here sorry.
no problem, ill figure something out
Hello everyone, I hope you are well!
Sorry to bother you, but I need help with physics :(
I need to add different forces to an object, but to be able to maximize the velocity that force will apply.
Basically:
A Wind script that adds a force (2,1) but will add no more than (5,5) in velocity.
A Movement script that will add a force depending on the input, but will add no more than (20,0)
A Jump script that adds an impulse force of (0,15)
Do you have any idea how to do this?
what are you trying to do
this is also pretty confusing
what are you trying to do
re-create the list every frame would be a huge boost to performance
i speculate creating a 100 element array every frame has no meaningful impact on performance. focus on correctness before optimizing
say I have a class that i created using a constructor with several parameters
i would then like to create a "copy" of that class by passing those parameters again into the constructor
for that im using Activator.CreateInstance()
however, due to inheritance, some constructors use more or less parameters than their parents constructor, so when its more, i override the Activator call and call it with the correct parameters
and i could do that with less parameters too, or give them a constructor with parameters that i dont use, but i have a lot of those classes to make an override method or an additional constructor for in that case and was wondering if it is possible to just pass more parameters than needed and have it dynamically choose the constructor to fit as many parameters, and drop the ones that arent used
design each layout, then design the regions of the screen where that layout should be active.
i would then like to create a "copy" of that class
you cannot shortcut authoring a copy constructor. there is a reason it isn't shipped in the c# language by default
if you need to copy, use a single class that can store many different kinds of data, instead of many classes each with little pieces of data
what are you trying to do?
what is this for?
Activator.CreateInstance()
this is a code smell. it means you are doing something wrong
If I add a force to my object (2,0), its velocity will keep growing. I would like the maximum velocity generated by this force to be (5,0) for example. However, I can't just clamp my velocity because if I have another object that affects the velocity of my object, it will conflict with the first force
for example if i have the method
public T Method<T>() where T : Foo
{
return Activator.CreateInstance(typeof(T), someString);
}```
then Method<Foo>() works fine but Method<Bar>() throws an error as there is no constructor with a string parameter
and i would like to know if its possible to still get that empty constructor even when i pass the string (as the alternative would be making a Method override for each child class with the correct parameters or creating a constructor with a string and I have quite a few child classes)
what is this for
it's too abstract
what are you trying to do
i would like to make a copy of a class instance that keeps the constructor parameters that i used on the original
yes, but why
@merry hill i'm worried the answer isn't succinct lol
don't tell me what you're engineering or how
just tell me what htis is all for
i believe in you
you can tell me succinctly
not my first language, trying to find the words, gimme a minute :P
yeah now that i think about it theres probably a better way
because i have a bunch of static instances of those classes as presets that id like to create non static copies from to use
for example i have a preset for a certain type of wall you can place and id like to create a wall in the scene from that preset
(bad example, theyre not just GameObjects to Instantiate, rather class instances)
Right on, I’m just struggling to figure out what the issue is as my player loop takes 2 seconds a frame to complete but the non-jobified version of my code can run 300 boids at 30 fps no problem
And I’ve heard that transform access arrays are expensive
Right on, I’m just struggling to figure out what the issue is as my player loop takes 2 seconds a frame to complete
you are probably using the jobs api wrong
why are you creating copies of class instances? what is the game? what is an example?
why do you need something so generic?
even if you had 100 classes you needed to copy, authoring 100 Copy methods will take around 1 hour
which is nothing
you probably have only 5 classes you need to copy
ever
you might be able to reduce it to like 1
but you have to tell me what you are trying to do
Yeah I’ll go ahead and see if I can’t refactor my code I wanted to learn how to use RaycastCommand’s anyway thanks you’ve likely just saved me a few hours of trying to figure out the problem
if the thing you need to copy is mostly primitives, struct copies "for free"
because id rather do it once now than a lot of times later but i guess itd really be easier to just do it manually with an extra constructor
okay
what are you trying to do
why do you need to decode a JWT in unity?
there are many libraries that do this
I'm logging in through the api and it returns a token with the data, and I need to decode this token to access the data
gotchya
well surely you've found a library
to do this
it's in google
what data are you expecting to decode from this token?
I found a tool from the staff that they put on github, but it has an error that I don't understand the problem
hey guys I am trying to implament a state machine for an NPC, that npc can hear sounds, and if he hear a sound its priorities change to that action, is it good idea to make a parent substate "listening" and having other children substate like "iddle" and "patrolling"?
oh and another thing, right now I have the code to search for a new waypoint to explore into the idle state, should I create a separated state to define the next point to explore?
what error ?
KeyNotFoundException: The given key 'alg' was not present in the dictionary.
staff?
might be worth to attach the debugger and halt there to see what is in the headerData Dictionary
sorry, not fluent in english, i use google translate to help
On jwt.io they have a list of libraries, have you tried the .NET ones on there?
this?
Yes.
I did not try 🌚
first time using, i will try
In Unity Test runner with performance benchmark extension, how can I make a build for testing that is not a Development build? What is point of benchmark extension if they don't allow that by default? 😕
https://docs.unity3d.com/Packages/com.unity.test-framework.performance@2.4/manual/index.html
The documentation says
Important Note: When tests are run with the Unity Test Runner, a development player is always built to support communication between the editor and player, effectively overriding the development build setting from the build settings UI or scripting API.
But they don't suggest any workaround
I tried building and running from command line, but seems like it still generates development build
This looks like just building regular game executable not for test runner
What is RunTests?
true that, it is, oops
Where did you get this code from?
Don't tell me it's ChatGPT-generated
When does an assetId ever change (if ever)?
Nah, my google-foo failed me. It can only be dev builds like you alluded to.
Just tested, only case i could see where it changed for me was deleting it and re-adding it to the project. Changing between folders showed the same id.
Dope thanks for the check
Try this:
var payloadBase64 = jwt.Split('.')[1];
switch (payloadBase64.Length % 4) {
case 1: payloadBase64 += "===";
break;
case 2: payloadBase64 += "==";
break;
case 3: payloadBase64 += "=";
break;
}
var payload = Encoding.UTF8.GetString(Convert.FromBase64String(payloadBase64));
// use your favorite json decoder here
It's literally only my setup. I have a root canvas and all my UI elements parented to it.
The user can manually zoom the camera.
This change of orthographic size triggers a full canvas rebuild.
What Unity Gaming Service do I need to use if I want to put non player specific data on the server for all players to fetch from (e.g., Character Base Stats).
I have had this issue I just reverted my editor
which platform are you targeting? what is the game?
what's the idea?
not really sure what you're getting at
it lags in the editor
it doesnt in the build, but i still care about it
im using overlay canvases now
it fixed the lag 100%
yep
you said some unspecific stuff about something
didnt expect camera space canvases to perform so poorly
then it sounds like you chose the fix that already worked for you
i don't think that's the issue
what are you referring to
yes it literally is
the documentation itself states the the canvas rebuilds on camera change
i don't think #archived-code-advanced is for you
all other channels dont make sense either lol
i think you are a #💻┃code-beginner which is okay
lmao
whats the point of an idiot like you trying to help if you just end up trying to unsuccessfully roast people
i dont think this server is for you
this is going to be hard for you
i cannot tell if you are using a testing endpoint, but you posted a JWT, which are all bearer, for something that interacts with a crypto wallet, and also this token expires Jan 03 2023
so i think you are in some jeopardy
you probably want to work with this API on a separate server
you can't login through an http POST API and get a valid token back, and also be part of something that actually works
so if you posted a username and password to something, and got back a JWT, it's already sort of screwed
for example, when you tap login with facebook, login with google, login with tiktok or whatever - do you observe ever putting in your username and password in the app that offers those login options? no, you are navigated to a website
is it possible to have a button as an arg to a method and use it to later end a task that that method creates? I tried to do it but i probably have incorrect syntax
it works when the process is public static but not otherwise
I begin the process later in the code
this just comes up with process not found
Is there any way to get around the fact that any gameobject in the scene can call public methods on your scripts?
For an example, I have a game object that interacts with the UI, but instead of the UI, any game object in the scene can modify its parameters instead
How can I avoid casting like below?
public interface IProfession
{
void Do(Task task);
void Cancel();
}
public class Builder : MonoBehaviour, IProfession
{
private void Start()
{
GetComponent<ProfessionCollection>().Add(TaskType.Build, this);
}
public void Do(Task task)
{
// run logic
var taskData = task as BuildTask;
//taskData.Data.Path
}
public void Cancel()
{
}
}
There are different tasks and professions
Task (BuildTask, CarryTask, etc.) --> Data Profession (Builder,Carrier,etc.) ---> Logic
Data (Task) are inside queue (priority queue). After dequeue, A specific job should start with that data
Queue: Task1,Task2,...,etc.
Dequeue: Task1 (Task)
BuildTask (Data)--> Builder
CarryTask (Data) --> Carrier
ReadWriteBuffers are restricted to only read & write the element at the job index. You can use double buffering strategies to avoid race conditions due to reading & writing in parallel to the same elements from a job.```
I could use some help understanding the last sentence of this error log, how can I solve this? I understand that it only wants me to access indexes of the array that are of the same index as the job index but I dont know what a double buffering strategy is?
double buffering is having two arrays, one with data to read from, and one to write from. If you then want to repeat the logic, you swap the arrays (reading from the one with the newly written data).
If you're aware of what you're doing and you know you're only reading and writing from an index once, like if you've just offset the index by a fixed value, then you can also just mark the collection with [NativeDisableParallelForRestriction]
This makes sense in concept but I guess I'm a little confused still
allignSteeringForce = rb[index];
for(int i = iTotals[index]; i < fTotals[index]; i++){
allignSteeringForce += (Vector2)velocities[i].normalized;
}```
In this example I'm just adding forces from multiple indexes into one variable then adding that variable to an empty Vec2 list would ```[NativeDisableParallelForRestriction]``` be valid in this context?
iTotals is the start point and fTotals is the finishing point essentially
Are you only reading from velocities?
Yes only read
If you're only reading from collections you should mark them as [ReadOnly]
Gotcha will that fix my issue? or is that just a general good idea/practice?
If they're read-only then you can access any index because there can't be a write conflict
Ahh gotcha thanks so much 😎
Note that you should also use [WriteOnly] where you can. Not only does it help with this sort of thing, but it also fixes warnings that can happen when you've scheduled jobs together that read or write to the same collection. I would like it if they were inferred when the code was compiled, but for now it's good to get into the habit of using them wherever you can.
Yeah I saw the readonly and write only but had no clue what they did outside of restricting what I could do with the array. Makes sense now 😎
?
what do you mean? what are you trying to do
do btnStop.onClick.AddListener(() => EndPythonProcess()).
I doubt there'll be a logic difference there. The issue is probably more to do with how the process is being started, not the button
Seems like using generics in some way should be the solution here. I don't have time to actually figure it out for ya, but typically generics are my go to for situations where I need to potentially pass multiple types into a function without necessarily knowing which one.
How could I go about returning values from a job? I have a job that calculates a Vector3 velocity to apply to a rigidbody but you cant apply it inside the context of the job so how can I re-assign the value of velocity[index] so that I can read the changed result in a job manager
or even is there a way that I can have rigidbody's in the job? (I couldn't find any real helpful resources on this)
OK, so Im making a game that's similar to Besiege, you build machines out of parts, and I have a gameobject called builder which renders the UI for building, as well as has scripts on it relating to using the parts, moving them around. I want these scripts to communicate with each other, but this creates the problem of exposing methods to all other scripts in the scene, so now, theoretically, any gameobject could add a new part to the machine, and it is not supposed to have that level of access
Guys, I have this error in the polaris asset, but it only happens when I create my scripts, as if it were conflicting with my scripts
hmm. that doesn't really matter
you own 100% of your source code
so you can always go and change the access modifiers anyway
they are as much of an agreement with yourself as "i will not use the wrong methods"
do you see what i mean?
Idk i just don't like it
I can't change access modifiers because I need the scripts on the builder object to communicate with each other
So yeah I can make an agreement with myself
But it just seems wrong
hmm
what i am sayin gis, the access modifiers are also an agreement with yourself
i appreciate you are trying to do this stylistically in a consistent way though
And why am I attaching code related to UI and other non 3D things to an object in 3D space
Just seems unintuitive
i don't know what that really concretely means. it seems reasonable to me that you have a TooltipOnHover script attached to a 3d object, whose job is to show 2d ui elements
for besiege, some stuff is tightly coupled, other stuff is decoupled. it's impossible to do 100% one way or the other
and stay sane
Well, there's a script for the UI toolkit rendering
And responding to button clicks etc
That's the UI part
That communicates with other scripts like, the tools, move, rotate, etc
All this is on one "builder" object
Which is a gameobject that doesn't render
Just holds scripts
I say it's a 3D object because it's in 3D space shared by the other game objects, has a transform
I have a scriptable object which contains data which is many classes deep. Prior to calling AssetDatabase.CreateAsset(scriptableObject, path), every field of the scriptable object is set correctly. But, afterwards, one certain type of field becomes null afterward. I have tried adding [SerializeField] to the field in question, but that does nothing.
The field in question is not a unity object.
The field is a custom class which extends Collection.
The field definition is like the follow:
[Serializable]
CustomClass : Collection<WrapperClass<ClassToWrap>>
and WrapperClass and ClassToWrap are marked as [Serializable] as well.
In addition, the field does in fact show up in the unity inspector. It just does not get serialized correctly it seems.
Any idea on how to fix this?
Don’t inherit from Collection and use List or array.
Do u mean inherit from one of those?
Is it possible to fix the issue without doing that? That would require a relatively large refactor.
You cannot serialize something that Unity does not support. Look into serialization callbacks and see if it helps your case.
I mean I tried marking everything including every field as serializable. Isn't that basically saying to unity that it can support serialization?
Collection is not supported
Wait, really? This says it has the serializable attribute https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.collection-1?view=netframework-4.7.2
Just because there is [Serializable] it doesn't mean Unity supports serialization for the class
Ah i see! Thank you! This page has the info I was looking for https://docs.unity3d.com/Manual/script-Serialization.html#SerializationRules
how many instances of this scriptable object do you have
how much data is in this object? like how many lines of yaml is the .asset file that corresponds to this scriptable object file
We constantly have issues with Scriptable Objects. Changes to Scriptable Objects don’t show up in github commit changes.
has anyone experienced this?
any advice on how to mitigate these issues?
Make sure you have hit Save Project, not just CTRL-S
I personally always rebind it to ctrl-shift-s
Not sure, I can check tomorrow. It's 8mb for the scriptable object.
Only 1
Thanks but You are sure generics works here?
Task type is base (parent) class. I want to map task data to the corresponding logic type.
Queue: Task1,Task2,...,etc. (Task type) Dequeue: Task1 (Task) BuildTask (Data)--> Builder(mono) CarryTask (Data) --> Carrier (mono)
Make the BuildTask call Builder
Cannot
I said, Task types are just data
After dequeue, a system decides which worker (builder, carrier,etc.) should handle it
You’re already using inheritance and have coupled type and worker
It’s not like you cannot, more like you don’t want to.
Sure, if you don’t want to use virtual method then only option is utilizing type information, which is casting.
Appreciated, but you mean call builder inside BuildTask. Yes, if they are coupled, it is OK
public class BuildTask:Task{
public BuildTaskData Data;
public Builder builder;
public override void Do(){
//...
}
}
Instead of
public class Task{
public int Id;
public int Priority;
//..
}
public class Task<T>:Task{
public T Data;
}
public class BuildTask:Task<BuildTaskData>{
}
public class Builder:MonoBehaviour{}
You can pass the parameter where Task can find builder
Or carrier, task can decide what to find
lets say you have to save up layers the best way you can.... Im thinking to group certain layers in 1 but i need at certain point to be able to discern between the raycasted elements to take different actions... I thought about using the different components the gameobjects have but the GetComponent is expensive... so i thought maybe to use the gameobject name
for example i had layers Animals, People
Im thinking to merge into "Npc"
and all animals would be instatiated with a name "ani_xxxx"
so when i raycast npc i would know by the name those who start by "ani" are animals
Is this sollution bad? do you have any other better?
Use TryGetComponent
but thats expensive isnt it?
or tryget is not as expensive as GetComponent?
expensive relative to what? TryGetComponent doesn't allocate if the check fails, so its slightly better and more concise
slow
TryGet is about 10 times slower than a direct (cached) reference
it takes on the order of 20 - 80 nanoseconds
yeah i know, thats why im asking if there's any alternative to discern gameobjects in the same layer (Besides using components)
like using the tag
but im scarce on tags too
TryGetComponent is the best way in terms of modularity, robustness, separation of concerns and overall maintainabiliy
uhmm. OKay you convinced me
😄
thanks a lot @compact ingot , whats the bad part on doing the name approach i suggested? several guys told me thats a bad idea but no one told me why
Tags are just Layers without the limit of having just 32 of them and also without any performance optimization
i had understood comparing tags was extremely fast
multiple reasons, names can change easily so code relying on them breaks easily, also names compare strings which is considerably slower than comparing integers or in case of layers a bitmask
these are all relative terms, you need to define what your reference of "fast" is
TryGetComponent is extremely fast when compared to FindObjectOfType<Foo>().First();
I always wondered why anyone would use First()...
yeah id never do FindObject
but now i see i can use as many tags as i want.....
hmmmmm
to get the first item in the returned enumerable of potentially many items
yeah i guess youre right anikki
yeah but it's the same as ?[0] except it's LINQ so probably slower
an IEnumerable has no indexer
and Linq is by no means slow, this is a complete myth perpetuated by people who don't understand what it is
an enumerable starts from it's first index tho, doesnt it? so u can do one yield on it
an IEnumerable has no concept of an index
my bad. I meant first returning value
an IEnumerable does not even guarantee that any item is in memory yet. It is a (potentially) lazy collection, which gets evaluated only when the item is accessed, i.e. by .First()
i meant sth like this
(do a reset() before, if the list is already iterated through)
idk what you mean
lets say events is our enumerable and we want to get it's first element without using LINQ
sure, but why? linq does the exact same thing (but optimized depending on the actual most derived type of the IEnumerable)
that's exactly my question too, wise versa tho. that why would we use First() if the alternative does the same thing in 1 line too 😅
btw, you can do
Enum.GetValues<VerboseFlags>()[0]
well that's an array, yeah
anyways. if it's alright, I'll repost my earlier question :p
Question: imagine red circle is cornered & is still, and green circle collides with it. during this OnCollisionEnter2D, when I apply the blue force to the red circle, what happens is that the red circle stays still, and the green circle receives the blue force and gets bounced back.
does anyone have an idea how to make the red circle have that blue velocity?
- I tried applying the blue to velicty
- tried applying it to AddForce with both Force and Impulse params
the semantics of .First() are that it will defer evaluation of any underlying data query until the very last moment and it will not allocate any collection. If you allocate that collection anyway you'd only use .First() for aesthetic reasons.
Also consider that Linq is implemented in a way that you can provision its queries with optimizations for a given (custom) data structure and make these optimizations transparent in code that only is concerned with expressing the query (and not optimizing it every time)
it would be physically correct if both started moving, assuming both have mass 1, at half magnitude of the blue vector (assuming zero bounciness)
yes bounciness and fraction are both zero. for some reason, the red stays put. when I log it, it gets the blue velocity for 1 frame, then it zeroes out the next. my guess is that the two circles can't go into each other's side if they move towards each other because of some physics rule or something. but i cant be sure about it really
even if I set the blue velocity to a crazy high value, the red stays put...
I can't fully understand what you mean. my EN isn't perfect so it could be that.
if you mean to consider that LINQs are usually there for easier data structure rather than super performant methods, well yeah, that's their sole purpose. I use them a lot. My issue was only with the First() extension that seemed redundant to me. as we can already get the first index of any index based list by [0] and as for IEnumerables, well, it's bad structure to want the first index out of an IEnumerable anyway
also, if it helps, this is the source code for First() extenison (formatted to reduce text size)
public static TSource First<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull(nameof (source));
if (source is IList<TSource> sourceList) {
if (sourceList.Count > 0) return sourceList[0];
} else {
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
if (enumerator.MoveNext()) return enumerator.Current;
}
throw Error.NoElements();
}```
as i said, it does exactly what you posted as an example above
this is completely wrong
If the black walls are static, the red ball is at rest and the green ball is hitting the red one, neglecting the direction of the velocity vector, what happens is that the energy from the green ball is passed over to the red one, then the red one passed it over to the black walls, that pass it back to the red ball, that passes it back to the green ball. Result, the green ball files back to where it came from and everything else stays still. The blue vector gets added up to the resulting one. It's physically correct as per I understand it.
Ah, I see. thanks. do you know any trick to get the red circle moving too?
LINQ is designed to be a unified API for all types of data queries and its particular power lies in its ability to consume custom implementations of how the underlying data structure is accessed (be that a database, list or anything else), this also means that it can be particularly fast without the user of the API neccesarily having to care about how to make it fast. Ofc this has limits, but it would be false to say Linq is "slow" because it can be used in sub-optimal ways. There is no redundancy in having [0] and .First(), they are completely different conceptually and semantically, even if in a special case they yield the same result.
Keep in mind that we are talking about rigid bodies
yes
The trick to have the red circle moving would be to add the blue vector to its velocity right after the "second" collision with the green one, not sure how to implement it though, I'm not at the PC right now
oh so they might have 2 collisions. makes sense! thanks a lot!
Try to log every collision from the red circle point of view, I am not sure how unity handles this, from a logical point of view you might have up to 4. You want to apply your blue vector after the last one btw
Your trigger might be when green circle starts moving backwards
but it would be false to say Linq is "slow"
well, LINQ is objectively slower than doing something manually the right way 🤷♂️ isn't that right?
There is no redundancy in having [0] and .First()
look at it this way. if you have a class that has index operators, you use[0]and notFirst(). if the class doesn't give you an index operator or any native way of getting it's first element, then it's clearly not supposed to be accessed in that way
right 👍
@oblique obsidian seems it all happened in one iteration
logs are all from the red circle's object. 1st two colliding objects are the black walls. the player 7 is the green circle.
the velocity gets zeroed out even if the blue force is a really big value
these are the red circle's rigidbody info during contact
you mean with RaycastHitAll right? i would use components. it depends what you are raycasting and how frequently
i only use layers for collision rules and camera rules. using them too much for logic is painful
@oblique obsidian solved it by increasing the red circle's mass to be greater than green circle
This is not correct, you need to use same IEnumerator you are using, MoveNext should be called first, and Dispose them afterward
First() is shorthand for all that
Interesting!
Sorry I was outside for groceries and stuff and I missed the messages
I am having trouble with giving objects velocity when parented
I am making this vr game that involves throwing an axe
by using the controllers local velocity
so before I give it its throwing direction I unparent it, for it to be thrown outside of the controller
but for some reason, it decides that it should be thrown in the direction of the original player's direction then the direction I'm giving it
Good afternoon, my name is Adrian and I am making an augmented reality application to present it in a national competition but when compiling I have this error if any of you can help me I am eternally grateful and thanks in advance
does unity support serialization for classes that implements IList?
ok. does it support anything like that, or am i best off creating a wrapper class for a list?
The only collection types it can serialize are List<T> and arrays. This might be what you mean by a wrapper class, but if you don't already know, you can can implement ISerializationCallbackReceiver in your own serializable classes to automatically convert data to and from types that Unity can handle.
ya that might be easiest to do (re: SerializationCallbackReciever). Then I don't have to rewrite the whole class
CommandInvokationFailure: Gradle build failed.
C:\Program Files\Unity\Hub\Editor\2020.3.41f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin\java.exe -classpath "C:\Users\adria\Downloads\gradle-6.9.2\lib\gradle-launcher-6.9.2.jar" org.gradle.launcher.GradleMain "-Dorg.gradle.jvmargs=-Xmx4096m" "assembleRelease"
Environment Variables:
RegionCode = LA
USERDOMAIN = GAIBOR
ProgramFiles = C:\Program Files
TMP = C:\Users\adria\AppData\Local\Temp
PROCESSOR_ARCHITECTURE = AMD64
PROCESSOR_REVISION = 7e05
OneDriveConsumer = C:\Users\adria\OneDrive
What's the method to raycast on screen pixels, when I want to ray cast on many screen pixels at once? Is it just like looping through Ray ray = camera.ScreenPointToRay(new Vector3(0 to screenWidth, 0 to screenHeight, 0)); ???
or is .ViewportPointToRay better if you want to take FoV into account?
set your android build level to 31 in both fields in player settings
that's what it is probably telling you at least
otherwise you have to find the real logs
you should also be using a different version of the editor ify ou're targeting the quest
Does anybody here know how I can get pixelsize using ortographic size and rendertexture sizes? This is what I'm trying to do:
float yOffset = campos.y / pixelSize;
Vector2 offset = new Vector2(xOffset, yOffset);
Vector3 snappedCamPos = new Vector3(Mathf.Round(xOffset) * pixelSize, Mathf.Round(yOffset)* pixelSize, campos.z);```
I can't for the love of god figure out how to get the size of a pixel
I somehow need to piece ortho size together with aspect ratio and rendertexture sizes to get a pixel size variable
and it breaks my brain
A size of single pixel in world would be (Ortho size * 2) / Texture height
Is that what you want
Possibly?
I need it in order to divide the camera's position by that value then round the result to get a pixel perfect transform
not an advanced question
@digital knoll Don't cross-post. And instead of spamming the question everywhere rephrase it so it can be understood clearly what you want to do. In #💻┃code-beginner
Okay, try the formula I wrote
How come this freezes the UI when pressed and how would I format this to not?
How do you return a value from an async function and not freeze the UI
you're doing Thread.Sleep in your task and then awaiting that task
don't await it
im doing that to test it
the thread.sleep
how would you make it run in the background regardless
or does thread.sleep affect not the current context
like does that affect the actual main thread
It's only affecting the main thread because you did await on the main thread
hm
even if i dont use await it still freezes
i felt like i already tested that
lol
should the RunDiagnostics not be async?
nvm i put await in the method and it worked
thanks
very cool
Any ideas why I'm getting a 64 length array when I'm getting the pixel data of a 256x1 texture?
Im not able to figure out a reason why that would be. Could you share the code?
It seems it was because I requesting Color instead of Color32, although I'm not sure why that is
Maybe the method doesn't support it, it has no type checking on the generics 🤷♀️
Im not sure what you mean by ”reuesting” in this case but Color has 16 bytes in it and Color32 has 4 so thats most likely it
I think it the type supposed to match with your texture format?
GetPixelData does not allocate memory; the returned NativeArray directly points to the Texture system memory data buffer.
So it's not going to convert type for you
The texture type is RGB9e5Float, what kind of value type do I use for that? 😅
Maybe I'm better off with a Color32[] and SetPixels32...
I guess you need int and bitwise operators to deal with it... 😅
how would I pass a returned value into another method without crashing my game lol
anytime i use .Result my game crashes
is there a specific way to do this?
Check each frame if it's completed
when it's completed, then you can read the result.
So use a co routine?
What would the syntax of that even be
Like how would you tell it to wait without await
IEnumerator MyCoroutine() {
yield return new WaitUntil(() => myTask.IsCompleted());
Debug.Log($"Result is {myTask.Result.ToString())!");
}```
Use UniTask if you want to do this elegantly with the async/await stuff rather than a coroutine
Okay thank you I’ll test that
apologies i had to drop my brother off somewhere
is unitask not installed?
like is it external
is it possible that altering a variable/reference which is being used by a coroutine can cause the coroutine to stop? (undesirably)
nw
im using a coroutine to animate a UI element, and I'm trying to make it input-spam proof. But if i spam it (edit the target value that the coroutine animates towards) from the editor, then it occasionally breaks.
the coroutine appears to just stop without running its final code
ok i think i narrowed down the cause to the editor itself
doing this with actual inputs rather than spamming the inspector at runtime seems 100% stable
I chose to use this thank you it works
How do I Texture.PackTextures() normal maps? Right now it's showing these weird seams.
And I think it has to do with how unity formats the channels of a normal map, and Texture2D.PackTextures doesn't automatically support that.
Hey all, I made a stupid mistake and need a quick bandage until I can fix the larger issue. I have several scripts, Foo and Bar that derive from a base class we'll call BaseFooBar. Foo has a field called SomeBool and Bar does not. Because I was not thinking ahead and made these classes long ago before I realized what I was really doing, I made a script that gets a component BaseFooBar and gets a value for SomeBool:
...
if (GetComponent<BaseFooBar>().SomeBar)
{
...
Now, I know that I need to go through and fix this issue properly but that's a larger issue because it's not quite as simple as a couple of classes. I absolutely do intend to fix it properly. However, I need a quick fix now. Is there a way to check if a component has a particular field before checking its value?
I'm er.. No i don't think thats possible
Maybe with some weird reflection? but thats beyond me
if SomeBar physically doesn't exist, there can be no check to see if it exists
I know in base C# you can usually do a type check for the field. I'm not sure how that would apply (or if it even can apply) to a component
like if (type.GetField("MyBool") != null
Yea you can get a list of fields/properties with reflection. Alternatively you could differentiate the classes by throwing an interface on the types with that field present and checking against that
Components are types like anything else in C#, so any reflection material for getting fields would apply.
Would it be something like this:
Type type = GetComponent<BaseFooBar>().GetType();
if (type.GetField("SomeBool") != null)
{
bool myBool = (bool)type.GetField("MyBool").GetValue(obj);
}
I really just need to go through and fix this properly. Looking at this just hurts
If you just want to access the SomeBool field on from the Foo class derived from BaseFooBar, just cast to Foo
var baseFooBar = GetComponent<BaseFooBar>() ;
if(baseFooBar is Foo foo)
{
foo.SomeBool = true;
}
Unless I'm misunderstanding the point of this 🤔
feel there is never a case where i would want to get a field by name like that with reflection
where just casting to the concrete type of a interface that has what you wants would not be better
What on earth are you trying to accomplish here
also would never try reflection logic like that for runtime in a game
Unity:
I am trying to stop the compile errors I get from the fact that a script is trying to access a variable on a script that doesn't have that variable.
If it doesn't have the variable why are you trying to access it
This seems like something that would be solved pretty simply with interfaces or abstract classes.
I have several scripts,
FooandBarthat derive from a base class we'll callBaseFooBar.Foohas a field calledSomeBoolandBardoes not. Because I was not thinking ahead and made these classes long ago before I realized what I was really doing, I made a script that gets a componentBaseFooBarand gets a value forSomeBool
I absolutely do intend to fix it properly. However, I need a quick fix now. Is there a way to check if a component has a particular field before checking its value?
Right now, the script is like this:
...
if (GetComponent<BaseFooBar>().SomeBool) {
...
and again, this is a simplification of a much larger and complex setup.
This is some #💻┃code-beginner stuff to be perfectly honest.
if (myObject is Foo f){
bool b = f.SomeBool;
} ```
also really would try and rethink you structure instead of hacking something ontop like this
I'm going to quote this for the third time:
I absolutely do intend to fix it properly. However, I need a quick fix now.
Like, seriously, I know I did it wrong, and I am going to fix it. I am asking for help for the moment so I can solve a more pressing issue
Imagine the fact that I am admitting I did it incorrectly and that I am going to fix it, and still people feel the need to condescend
people are not trying to condescend, they simply know the path you were going down turns into a much larger headache later on
This is some #💻┃code-beginner stuff to be perfectly honest.
That is condescension.
but yeah if doing this, would leave reflection alone and do the is example like @sly grove suggested
Alright, I have tried using is however it's not quite going to work that way due to the way access is set up in this case. Which is to say that, currently, the script cannot access Foo, it can only access Bar.
so issue is using reflection is fragile, slow and will make it harder to refactor later
its really mostly useful for tools that do stuff with code, or for editor tools
Right, totally. I'm essentially at the "I just need to get it to compile and fix XYZ", at which point I can fix the issue properly.
Do not use reflection to evaluate if the class has a particular member. Instead, cast to the specific with as. Since you know that you're looking for a member called SomeBool that Foo definitely has, you'd want to attempt to cast to that type. If the cast fails (null), it'll definitely not have the member.
or via is like suggested so you can check that it can be cast and cast at the same time
is isn't currently working. I can try as to see if that at least gets it to compile, since I don't care about if it works at this point
Right, but the script performing this operation cannot access Foo.
why not
What do you mean by cannot access Foo? It doesn't know of the type and it's existence?
if its a type in your scripts folder it can access it
since its all in the same assembly
Exactly. There are some conflicts in the access due to a miscommunication, which is a larger issue
if its in a other assembly its up to you to make sure its referenced correctly
either way if the type is not there, reflection will fail as well
since it also needs that type information
If you don't know what you're working with, you are in an unknown territory and headache valley. There is no salvation. Reflection, safe coding practice, and good luck.
No worries. I've been working on the better, more complicated, but more correct solution for a while now.
generally better solutions are not more complicated
It's just old mistakes from code I wrote a couple years ago that was done wrong, biting me in the butt
if you are going down the path of trying to access thigns on types you do not have, and using reflection. you literally would be better off deleting it and starting anew
That entirely depends on the problem. When refactoring is involved it can be much more complicated, but the result is better
also you never explained why you do not have access to the type
i been programming most of my life at this point in many languages, complexity is future tech debt
OK, so I mentioned this is a simplification, but basically it's not actually Foo and Bar. It's two different versions of Foo from two different things that were combined improperly. So there is a version of Foo that has SomeBool and a version that doesn't, and both derive from the base class in different namespaces, and the other script takes in the base class instead of the derivative
and for some reason one is in a different assembly that you cannot change?
Yes.
you jsut need to provide a alias or full name
Right, I just have to do that on a lot of different scripts that are stuck referencing the wrong Foo. Once that's done, then I can just remove the wrong one, fix the references, and it'll be fine.
It's a longer, but more correct solution to fix it. I don't mind
ok, but are they only in different namespaces
or do they exist in different asmdefs or different dlls?
Unfortunately, the issue is because of namespace capitalization
ok, but why cant a fully qualiifed name be used then
if its only about namespaces its easy to work around
or a alias in your using statements
There's not really a difference between Foo and Bar and A.Foo and B.Foo
Classes with the same name in different namespaces are just... Completely separate classes
You might know how Unity has issues when there is a capitalization difference between a script name and script filename. This causes some issues when git is involved, because git generally doesn't read changes in capitalization as changes
sorting out that is a way more solveable problem then what you are trying to do
Git has no problem with it. The problem would come only from case insensitive filesystems
also its not git, its windows that has the issue
Such as Fat32
Regardless of who has the issue, it leaves a problem when there are conflicts that don't appear to be conflicts.
It'd be quite rare in this day and age to be using a FAT32 partition
if you fix it on something that is case senstitive and clone it back cases will be all correct
So, as mentioned, the longer and more correct solution is to go through and fix all the references manually and reserialize everything. This would be much easier if I could get the code to compile, because at that point it should all serialize and I can just remove the conflicting script
as long as the meta file name changes with the file name, references will stay intact
I'm not bothered by having to do it the long way. I was only hoping to skip a step. No worries.
if you're going to fix it later, fix it now
If you just need it to compile but not actually work. Have you considered just... commenting the code out that is preventing the compile?
How do I properly use Texture2D.PackTextures() on normal maps?
** Does anyone here use UnityEvent's extensively? I see it a nice way to de-couple the code but as the progress goes it will be a nightmare to track which is changing what and from where. Any insights on it?**
Unity events when assigned in the editor are the most coupled and easily broken thing you can do. They are only a viable option to hook up notifications on the same object. They are not really events (which would be an implementation of IoC) but serialized method calls (which are decidedly not IoC)
If you want to have editor assigned messaging with actual decoupling/IoC and you are okay with the mess that can produce, you’d go with mediator SOs (the Ryan Hipple thing)
I use it a lot for my designers! But I would never use it myself or use it for anything complex.
An example:
Does anyone have a moment to help me figure out why my playerprefs manager script does not seem to save/load player prefs?
https://pastebin.com/hYR9VL5f The whole thing is here. It creates tokens for every settings option, identifies it via a string label and then just reads/writes the data according to the data type declared in the token
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Having used player prefs without any trouble in the past, I cannot figure out why this one doesn't work
(I'm doing all of my testing in build and the methods are all being called successfully as confirmed by debug.logerror prints)
Why this won't work 😭
@hallow elk you were looking for TryGetComponent, and "is" for pattern matching
What does this event manager do? It allows as a entry point for registering events generated from the components of this gameobject?
I see using SO's as a mediator more like the workaround for having shared memory problem. Please correct me if i'm wrong.
Why I see more like a workaround but not a proper solution is
- I need to have SO classes like for ever parameter combination (Float variable, Int, float +int and so on) which I see will work for smaller set
- If I go and create SO class for each event, creating an instance of SO from the class sounds more like a patch as i see only one instance object is required for that specific event. Which doesn't sound great.
By SO instance I mean the asset created from SO class.
But one nice thing is it shares the data nicely making whole thing decoupled If i compromise on some coding style.
@compact ingot
The unity events get invoked according to their appropriate collision event. You can then choose for example a script that the collided object needs to have to be triggered. This can also be a tag, etc. Or just to always invoke on trigger or collision
Anyone Please Help #archived-code-general
Ok. Nice!
But will this be easy to maintain for bigger projects?
Expecting Some to Check this 😦
UnityEvents are inherently not scalable but that doesn't mean they're not applicable to larger projects, similar to the script I wrote. It's more about "what" you use it for. If scalability is required for that thing, don't use it
Best way to get which side a cube has been hit?
if this was the wrong channel, please tell me btw haha
(1) yes, that is the entire point of it, maximising modularity and pushing semantics into the design space (this can be a good or a bad thing depending on your workflow/team needs & goals)
(2) idk what you mean, you'd create a new instance for all semantically different events, messages or data channels you'd need, the type of the SO and the semantics of it can be entirely unrelated (they could all be the same type). You are also free to use any struct as a value type for your SOs to facilitate complex messages (i.e. a Vector3 is a set of three floats, or an event may want to pass along source reference and some arguments)
The seminal Unite Talk (video on yt) on the subject explains all the benefits very well, just note that all the benefits can also be problems, depending, again, on your needs & goals.
You can solve the same thing in code only by using a dependency injection container or doing IoC with manual DI.
In no way would Unity Events "for everything" be a better alternative.
Best part with SO compared to code approach is SO being a physical asset, easy to manage. But code has its own benefits though.
Btw, do you mean creating a new SO class for every event type would be fine? That ways I see it more comfortable about the way its coded rather than having combinations of parameter type classes.
Also I wish unity creates something like a "data pipe" or message channel kind of things so that it won't more like a patch to how SO's are used in this context.
those "physical assets" can be a nightmare in source control compared to code or json say
far harder to manage in some respects
Is it? Won't they be easy to resolve(conflicts if any)?
Because it wont let us to touch the code and I see it more valuable
ymmv, but in my experience no - the scriptable objects and binary unity objects in general are much harder to keep track of
its not a "patch" or "hack", get that out of your mind, a mediator SO is effectively a message pipe
if you need an actual message pipe, use https://github.com/Cysharp/MessagePipe
it supports all common messaging patterns
if you are comfortable reading the yaml in .meta and not use binary assets (which you can't if you use VCS anyway) then you can review changes, but its far from nice
you also should consider writing tools no matter how you solve your problem. Much of Unity's systems are very low level and do not automatically provide a great UX without custom tools.
SOs can be very easy to manage with some simple custom editor windows
the issue (and opportunity) with SO events is rather in the creative use they allow, so parts of your game logic will not be visible in code, actually most of it wont, and this can create problems, also if your team is not 110% disciplined about naming conventions and asset organization, it will be a mess
What I don't like about using SOs for something like this is that you'll often end up with single instances of each SO type. That will quickly fill up the CreateAssetMenu, so you'd probably need to find some other way to create each instance.
you can make folders in the menu
Still, it's a menu you'd literally use once just to create the single instance required.
you can create assets with a button in a window or inspector too
or a context menu action
there are plenty of things in unity menus that you only ever create once
never even used this one 😄
So you mean, we need to ignore how the data pipe is created and only focus on its funtionality then. Is it me alone or do you agree that the SO's class can be very generic and the functionality it does is totally diff - this what makes me feel its odd.
For ex: Consider I create a SingleFloatParamEventSO and this will be used for diff types if events where single float parameter is required
VS
Creating a class which does point to concreate event name
Here the latter is more easy to debug where as first one tough to track down as the type is too generic in the code.
yes, its only useful if you create a FloatMessage and put the semantics int he instance name
if you do it any other way you'd be better off using a code based Message Pipe
This is what my problem too and this makes it look odd - may be personal opinion though
imo things like this distract from the actual issues, its completely irrelevant outside aesthetics and it is solvable anyway (custom windows, inspector buttons)
you can create buttons like this rather easily
btw, i'm not trying to convince anyone, just hoping that you decide for/aginst SOs based on actual issues/opportunities
Phew! So this is there. I was thinking i got it wrong. Thanks for clarifying.
Semantics goes in the instance naming which needs some good workflow to be all on same page. But I agree on most of your points, its definitely solving a major part.
i've had projects where i used SOs for UI data binding and config, ingame settings and maybe the odd global message but not for anything driving gameplay, so there is no requirement to be dogmatic about it
i'd probably advise against being dogmatic about any pattern in a game project
all these patterns become much easier to design if your team is 100% comfortable with the actual, real idea behind the inversion of control principle
I definitely prefer the code based approach and use it for my own event bus. Usage looks something like:
private void OnEnable()
{
EventBus.SubscribeTo<PlayerDamageEvent>(OnPlayerDamageEvent);
}
private void OnDisable()
{
EventBus.UnsubscribeFrom<PlayerDamageEvent>(OnPlayerDamageEvent);
}
private void OnPlayerDamageEvent(ref PlayerDamageEvent damageEvent)
{
Debug.Log($"Player received {damageEvent.Amount} damage");
}
Where PlayerDamageEvent is defined as:
public struct PlayerDamageEvent : IEvent
{
public float Amount;
}
MessagePipe looks similar but also screams enterprise/business
also much easier and more manageable if you have semantic types for each event
you can still expose these code-based event channels in the editor with some work on custom inspectors
Can you show a snippet of how the EventBus class would look with the PlayerDamageEvent ?
the event bus itself is completely ignorant of the type of event it brokers
Yeah I have that as well, you just need a non-generic version of the event bus methods and serialize the events either with [SerializeReference] or by type name.
Like Anikki said, the event bus class is generic and doesn't implement any of the events specifically. How you do that doesn't matter particularly. One way is to have a Dictionary<Type, List<Subscribers>> in the event bus so it can store a list of subscribers for each event type.
Gotcha, thanks
I had only seen the eventbus pattern in Godot, where its more or less just a bunch of named signals (events)
Looks like it's string based 🤢
Not in Godot 4, they updated GDscript so now they can be referenced as their own fields (thank the gods)
I prefer Concrete type over strings as its more easy to manage
So question is while EventBus is a very old concept which actually solves the problem in a better way, I wonder why SO's are being suggested for decoupling stuff*
Is it only because of less code - 🙄
Theoretically more designer friendly since they can be created and wired up in the editor.
The editor and serialized fields are a very powerful tool and it would be silly to avoid it. But I do think you can go too far, like going all in on ScriptableObject Architecture, where everything from events to variables are defined as SOs.
if you need all the reasons explained at length, watch the talk by ryan hipple on yt
there is nothing to add to his arguments and all the discussion is only about criticisms. what MentallyStable said is the conclusion you come to after trying it for a while yourself
you can't make an informed decision without ever trying all the options yourself, so whichever way you go, be confident its a valuable experience at least once. In any project you'll join (and don't write entirely yourself) you'll come across an unholy mix of every pattern ever invented and everyone will like you if you can just dive into it and start fixing bugs that eluded everyone else in their dogmatic worldview.
One thing the SO/linked-up-in-editor approach works quite well with is Addressables, new content and gameplay updates can be created in asset bundles without having to rebuild (and republish) the base game
I tried both(event bus and SO's) the approaches earlier and also unity events.
I recently noticed SO approach is more discussed on internet and wanted to see what I thought about it is proper or not.
I see both the appoaches are totally fine as you mentioned if team is in sync about the approach used. MentallyStable's eventbus is what something I personally prefer as its more concrete at code level. However SO's shine as its more manageable from non-coders end which is a big plus in diversified team.
@compact ingot However, i'm convinced about your explanation too when you mentioned about semantics of an event will be defined at instance of SO. So I now have proper understanding on when to go with SO approach. Thanks for the details!
https://answers.unity.com/questions/1934122/unity-ecs-10-generated-mesh-not-visible.html
I've been procedurally trying to generate voxel-chunk meshes in my game-scene in ECS 1.0.0-exp.12 (Unity 2022.2.0b16). In ECS 0.51, I was able to- but transitioning over caused the problem. As you can see, the mesh itself is being generated, but the render for it is not. Were there major rendering changes made to ECS 1.0? I would love some help on this and if any more information is needed, I'm happy to give it. Thank you.
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
I want to make a modular spell system with a graph view. By modular, I mean that i can mix and match different types of behaviour and make as many unique spells as i want. How should i approach it? The way I imagine it is I have components with events. I just add components that happen on SpellStart and then these other components to events from these components. Not sure how to implement it though. I have Odin inspector.
I find the public discussion on the internet on the subject rather amateurish. Very few opinions/experiences are shared by people that have released relevant commercial titles. Best you can find is people with experience in 1-5 person projects with 3-6 month durations or freelancers
Will there be any issues with meshes that have unused vertices ? I need to implement a lod stitching between segments and the solution I have in mind involves only regenerating the triangles and leaving the same vertex array. Which means that some of the vertices will be left unused. Are there're any non-obvious issues with that, like shaders acting up or something similar ?
Uh yeah I don't think it's great but... it's probably not going to hurt much. Mostly just wasted memory.
glad to hear
there shouldn't be much waste, as it only affects the borders and should produce very little excess vertices
having fixed vertex indices sounds like a good trade off in this case
best thing would be to get access to the same API Unity's terrain uses to generate LOD-enabled heightmap mesh, but seems like you just can't
I think unused vertices still counted for bounding box calculation
good to know,, thanks!
shouldn't be an issue in this case though, as they will always be aligned with the borders
Yeah that'd be fine
After moving an object with position.lerp my object kinda locks in and I cant move it even when i try to move it from the editor, any idea whats causing it and how to repair it?
You're trying to move it but your update is overriding the position
How do I properly use Texture2D.PackTextures() on normal maps? Right now the normal map appears reddish and seams are being shown when I try to use it on a model.
Its a coroutine to be more specific, but nonetheless seems like it, what can i do to stop it?
The last coroutine that moved the object has ended
Coroutine in update?
no, not in update
I'm kind of scared of asking what does StartCoroutine(Waiting(2f)); does....
I needed a fast way to wait 2 seconds, I know its a barbaric way of doing things
It's even more of a barbaric way than you think lol
Try
yield return new WaitForSeconds(2f)
What does it do tho, like how do you set up timer for 2 seconds???
No, I was just a complete moron and literally used that one line of code in a dedicated function
I suppose I cant have multiple yield return in the same function now can i
You can
You can have a whole queue of stuff that happens one after another
After a delay
That line will just wait for 2 seconds before proceeding to the line below it
That’s why yield keyword exists
Muiltiple return (with lazy evaluation)
Ok so I did that but it didnt do anything below my second yield return
no debug and didnt enter my function
Maybe the second coroutine didn't finish?
(Personally I've never used another coroutine inside a coroutine so no clue how that works)
what are you trying to do
Also Jesus Christ that's a lot of coroutines inside a coroutine
are you asking how to sequence things in coroutines, including other coroutines?
I see 3 just in that snippet
you are showing screenshots of snippets of code. based on the only thing that is visible there, SmoothLerp is buggy, or you are disabling the game object this script is attached to during the coroutine you are yielding on before the log statement
@fringe condor does that make sense?
smoothlerp is probably something like while not the value is equal to the destination value
something bad
it checks for a minimum distance between my object and its destination so its not like it is dancing around it
The function aint buggy as it functions smootly in previous uses (from the same session of play mode)
How would you do async tests like this? I am getting that error
so i dont really have anything else besides something breaking with the yield
If you used == to check, then yes it will dance around because values usually never become equal when used along with time.deltatime
And like he said, try using DOTween, it's much simpler and easier way to do it
no, it check if the distance between is less than some minError
Use [UnityTest]
whatre the differences?
i can look it up if its something deep
IEnumerator is something nunit does not support natively
Coroutine is Unity specific feature
ah okay thank you
this is the quintessential buggy behavior
you have to listen to what i am saying
and do it
if you want your thing to work
Can someone help me
private void RaycastForEnemy()
{
RaycastHit hit;
if (Physics.Raycast(transform.parent.position, transform.parent.forward, out hit, 1 << LayerMask.NameToLayer("Enemy")))
{
try
{
Debug.Log("Hit an Enemy!");
Rigidbody rb = hit.transform.GetComponent<Rigidbody>();
rb.constraints = RigidbodyConstraints.None;
rb.AddForce(transform.parent.transform.forward * 500);
}
catch
{
}
}
}
I cant get the bullet to do anything to the enemy
it's an example. It's not very #archived-code-advanced if you can't understand an example
my bad there was ppl talking in the other ones
That's not how discord works
ik I didnt wanna interrupt them
make a thread next time
alr
yeah 👍
i asked this on the subreddit but decided to ask here too.
I have some code using the new netcode extensions, with network objects and all that.
Are there any good cheap server-options that will allow me to incorporate that code? The prices on the unity servers are a bit high and a bit confusing... It also seems like you cant choose a free package that will be cut off/limited, instead you need to pay if you go over (Which is scary seeing as i need to test it for performance and such)
i have no experience with servers... I tried converting some code to photon too but it seems a bit buggy and possibly not for my situation...
For an idea of what I mean: I am trying to re-code katamari, so there will be a lot of objects that do literally nothing until touched... then they do something... then do nothing again until the player that touched them leaves or is defeated. (I dont need tips on how to code it, just how to connect to a server or allow players to go player-to-player with it)
Looking it up i cannot tell if other server hosts will allow me to use this code or do I need to swap. If anyone has any experience with setting up a server (p2p or dedicated) it would be greatly appreciated.
I have a generic wrapper class. Can I make for it an implicit conversion operator to all of its inner value's base types (interfaces) which will return the inner value?
The class itself looks kinda like this
public class DecorationProperty<T> where T : class
{
public DecorationProperty()
{
}
private readonly List<Func<T, T>> _decorators = new();
private T _value;
private bool _decorated = false;
private T _finalValue;
public void Decorate(Func<T, T> decorator)
{
_decorators.Add(decorator);
_decorated = false;
}
public static implicit operator T(DecorationProperty<T> property)
{
if (property._value == null) throw new Exception("No value to DecorationProperty");
if (!property._decorated)
{
property._finalValue = property._value;
foreach (Func<T, T> funcDecorator in Enumerable.Reverse(property._decorators))
{
property._finalValue = funcDecorator(property._finalValue);
}
property._decorated = true;
}
return property._finalValue;
}
public void Set(T value)
{
_value = value;
}
}```
I'm doing networking in FLAX, very similar to Unity
I have a dictionary with object + name (set to connection ID to tie incoming messages to an object)
Then I have a list with name + location
Trouble is I cant for the life of me use the name from connection ID to read the index of the corresponding entry in the list
here's a snippet of code where i try to get the index but it gives me an out of range error.
Surely if I JUST put that name in then it cant be too big to use to read right???
I have asked many code wizards and they just don't know where I should go from here
List<_ClientsHolderDefine> _ClientsHolder = new List<_ClientsHolderDefine>();
//Create the object
var Clientsholderinput = new _ClientsHolderDefine(name, spawnlocation, 5, 2.5f);
//Add it to the list
_ClientsHolder.Add(Clientsholderinput);
//Get the index of the Clientsholderinput we just added
int index = _ClientsHolder.IndexOf(_Clientsholderinput, (eventData.Sender.ConnectionId));```
It fairly obvious that ConnectionId contains a value >= _ClientsHolder.Count;
and btw why dont you just do
int index = _ClientsHolder.Count;
_ClientsHolder.Add(Clientsholderinput);
noticed now that i look again, been a long day. thanks
do you have a screenshot of your game?
I'm writing a source generator for Unity, and I need to include a file as 'additional files'.
Has anyone tried this before, and if so. How did you do it?
This is what the compiler option /additionalfile:Assets/hello.json gives me.
A bunch of InvalidOperationException: Failed to add object of type XXXXX.
InvalidOperationException: Failed to add object of type `SubGraphAsset`. Check that the definition is in a file of the same name and that it compiles properly.
UnityEditor.ShaderGraph.ShaderSubGraphImporter.OnImportAsset (UnityEditor.AssetImporters.AssetImportContext ctx) (at Library/PackageCache/com.unity.shadergraph@14.0.4/Editor/Importers/ShaderSubGraphImporter.cs:116)
UnityEditor.AssetImporters.ScriptedImporter.GenerateAssetData (UnityEditor.AssetImporters.AssetImportContext ctx) (at <f7044ab663d344a2badf1160e57d1c1d>:0)
this is how it looks when played (Photon is disabled, I have a different github branch with photon-based code on it)
The items on the ball are childed to it and running no code.
When childed, items and the ball read a few things, meaning having a host is better for anticheat.
(ignore the text in the top left it hasnt been fixed yet)
did you make the assets?
have you tried turning on shadows and making a nonflat floor?
it seems like you've been at this for a while
what is this for?
Just picked it back up again.
I'm trying to read a configuration file, that configures the directories the source generator should use. Just having fun with Unity and SG, thought I'd generate an enum based on all sound files in a specific directory, that way designers can easily implement sound effects without having to manually type out the names and/or write code (or use scriptable objects).
I've done it before, but I had to use PATH environment variable to make it happen, I would love to be able to make it PATH free.
Yes i made assets
Shadows will make the game REALLY laggy.
hmm
and what's the idea with multiplayer?
let's say there was no lag
let's say your players had 4090s and a EPYC zen4 96 core CPU
would you make it look different?
and how do you control it right now?
multiplayer works already
i just need to figure out how to get it onto a server
using unity's netcode another player spawns in and both can pick up items
There are projectile weapons that knock items off other people.
You control it with WASD but that can be changed
You can only control your own player when both are spawned in.
my main issue is i cant figure out how to get a server or a p2p syncer that will work with unity's netcode stuff.
i currently test the multiplayer with the networkmanager (From a unitypackage) and it has a button to start a host/server/clent however it always seems to be on localhost.
do you have an idea for how you could make your game work with touch? for example, for how to move the katamari in an intuitive way in portrait mode?
thats not what im stuck on...
hmm
i know, but you're actually at the start, not the end, of this journey
and i make a technology that makes this all a lot easier. i'm just seeing if it makes sense for your game
like multiplayer katamarci damacy is interesting to me
and i dont really know for touch, i've done a bit with mobile but i do want this to be a PC game.
i have a lot of ideas for the games, there are powerups that have been coded but they currently only work singleplayer
okay can you visit this link - https://appmana.com/watch/unity-starter-hdrp
and grab the marble in front of you
okay
do you see how it's the same unity scene, different cameras, different inputs
it's local multiplayer, it's clearly networked
because you and i just donked marbles with each other
do you get it?
interesting,
ye i do.
okay
i knew you would
it's local multiplayer but it's networked. that means your game is reality.
this is the scene - https://github.com/appmana/appmana-unity-starter-hdrp
you can do this in urp too
https://appmana.com/watch/theheretic but you can really do anything
two questions,
does this only work with mouse
would I need to re-write code that references other gameobjects?
it works with every input - touch, mouse, keyboard and gamepad
would I need to re-write code that references other gameobjects?
no. there is no netcode. it's like engineering a local multiplayer game, except you have multiple cameras
you connect your git repo, and it builds it and you have a link.
auto builds on push.
the plugin is extremely simple
you have to use input system. you would want your game to make sense for mobile, because then you have an audience
in the sense that you can share a link
and most people use their phones
as their computers
and they can Just Start Playing
just like you did with me
no faff
it's regular unity physics. no unity physics netcode synchronization warble garble. literally anything creative you can do single player, it works multiplayer
but of course all compatible with pc
i am just always on the look out for someone with an intriguing idea and skills
anyway think about it. i think you have a promising scene
you can add the plugin, it has only 1 script. then you add the git repo and you can mess with the link
you should be using input system anyway. that is the only compatibility issue typically for people to try
then you could e.g. use the obi physics packages
and do cool liquids, ropes and soft bodies stuff
and since the computers are extremely powerful, you can do whatever works well on your editing station
it will work well for the player
can you spawn in a new player object for each player...
because part of the issue is each player needs their own player object.
will it always sync every aspect of every object, or do i need to use some code to sync the objects player-to-player somehow
I dont really know where to get started with this.
can you spawn in a new player object for each player...
yes, that's how it works
will it always sync every aspect of every object, or do i need to use some code to sync the objects player-to-player somehow
there is no syncing. it's the same scene. it's 100% the same computer process, with two (or more) players sharing it
or do i need to use some code to sync the objects player-to-player somehow
there is nothing to sync. it's like a local multiplayer game
how does it sync, does it have a server it runs off of/is there ram etc?
I dont really know where to get started with this.
you can use the sample HDRP project, or you can add the plugin here https://github.com/AppMana/appmana-unity-plugin then add it to your account
a build system compiles your game, packages it and runs it in windows containers. a bunch of systems work together to connect users who visit a URL to your game, and set up a special kind of video, sound and inputs streaming that works with browsers. the backend systems ensure that people "load" a game instantly
the amount of computing resources you use are sort of negligible, so that's why the dashboard doesn't expose any of that. it doesn't really matter.
here's a single player game someone developed - https://appmana.com/watch/lbxx
the link you gave has an example for only a 2-player game, is it possible for any amount of players?
you can have more. there are some folks doing 6. in my personal opinion, as a game designer, targeting 2 is the Right Amount if you wanna have a real audience. if you have a big "free for all" style game, then it can make sense to have more
i am glad you are intrigued
i think people who wanna do interesting multiplayer experiences in unity usually wanna use physics
and then you run into this hole where networking physics is ridiculously hard
this is the only approach that lets you be innovative with multiplayer physics, as a single person
if we had $10m-100m budgets like Blizzard does, we can make networked physics as good as the kind in like overwatch
https://www.dropbox.com/s/w9qq40jb92a0ngw/Editor Experience.mov?dl=0 @severe tundra here's what it looks like in editor. observe there are two different game views, one for each player. the editor helps you instantly test two players with distinct input
the marbles are ordinary rigidbodies. there's nothing special. no scripts about networking in here
part of the issue right now is i need to remove some networking code i had in 😛
yes, this is definitely easier when you are aware of it from the very beginning
however you might want to experiment with local multiplayer anyway.
ye ill think about it
part of my reluctance is that i do have the code ready for multiplayer
i just have no idea how to connect to a server with said code. (Other than using unity's servers which seem overpriced)
for some inspiration for controls, you can look at my virtual test drive - http://appmana.com/watch/virtualtestdrive - this has tap, drag and swipe controls for driving
Stream apps and games directly to your browser. Join the waitlist.
it's worth trying that link on your phone
so you can appreciate how nice it is to have hdrp in mobile
i just have no idea how to connect to a server with said code. (Other than using unity's servers which seem overpriced)
in principle, for a small number of concurrent users (<10), you build your host, it runs constantly on an ec2 instance you spin up <— this is describing what you were originally asking about
you hard code your game to connect to it
and the server infers from the pattern of connections what to do
restart a game, wait for players, etc.
10 concurrents sounds like very little, but it's actually like 7,000-15,000 visitors from 9am-9pm, if a match is typically about 3 minutes
im not talking about your system with this comment, as the one im doing is moreso trying to connect to an ip or a server ip.
as of now all testing is being done connecting to localhost rather than a server
yeah
on aws, you would use route53 to set up a domain that points to something that supports loadbalancing / proxying, like traefik nginx envoy haproxy or whatever, that's designed to route users to a web server
each player's client makes a REST request for a match. a matchmaker sends back the connection information to the clients
unity sort of has this already. you can also deploy it yourself, it's called openmatchmaking, it is ridiculously complex to deploy
then your clients use the information they receive from the matchmaker to connect to a real unity headless server instance, also running on a remote machine
i am addressing what you originalyl asked about, not how this system works
this system you just give it your source and it builds the game
it does all of this on the backend. i wrote my own matchmaker
ah
im confused because im not fully sure how either system works
i evaluated openmatchmaking which is why i know so much about it
i think what's so confusing is that for multiplayer games, traditionally
you either have 0 players or 1,000,000 players
so nothing is engineered for in between
self hosted games work for in between, but those are sort of dead as an end user concept
too hard for people to do
self hosted meaning the end user's machine, if it's not an xbox, hosts the match.
steam also supports this. but understanding how steam networking does it all is another degree in multiplayernetworkology
what unity does is similar to what my system does. it starts -batchmode unity processes inside virtual machines on their/AWS servers, those servers connect to a matchmaker, your client connects to the matchmaker, the matchmaker assigns servers to clients, the clients receive that connection information and connect to those -batchmode unity processes
it is more complex
not necessarily in a good way. really depends on the game
tbh the main thing i wanted to be able to do is just have a main menu screen where you can type in a code
and if there is no lobby for that code, it makes one with you as host of the lobby
if there is a lobby with that code it would set you up as a client to that lobby
im sad there are no good videos on how to connect your code with one system to something.
The only one ive found that can connect to it is unity's own servers that are usage-based rather than package based so you cant force a cutoff.
yes, they are indeed usage priced because, well how else could it work
it's really complex software
the compute costs are nothing, that's true. it's literally pennies a year for unity to deal with your game
but you're paying for the software that makes this all actually work
in the case of a streamed game, the compute costs are much higher
lobby codes are still interacting with a matchmaker
this is the simplest matchmaker i've authored - https://github.com/hiddenswitch/Spellsource/blob/28066a21d264d0f9d08983ca7acd8f5f4acaa381/spellsource-server/src/main/java/com/hiddenswitch/framework/Matchmaking.java#L78
but like i said you can use openmatchmaking
which is tremendously hard to deploy. i mean it is very arcane
there aren't going to be any videos in any case. the number of people who know how to do this, the whole picture, numbers in the 10s in the whole world
it's part of this very long journey
at least if you want to make something that feels as polished as Clash Royale
or counterstrike.
openmatch doesn't deal with players disconnecting while matchmaking, for example
does your system deal with disconnection?
@severe tundra so for example, what if someone puts in a lobby code, then starts hosting a game, then unplugs their computer
as elegantly as it can
because one idea i had was just... a huge lobby that was agario but katamari.
it supports sandbox style multiplayer like that
where a game might have 10 slots, and people can join and leave those slots. like a traditional arcade game
and once every single player leaves, the whole match resets
arcade style matchmaking seems to be what most people want to do anyway
that is how the system works by default
you have an unlimited number of N player arcade machines, and players eagerly fill open spots in the busiest arcades
in my code items have a callable function that just return them to their spawn position and can be knocked off.
so if i had say, a disconnect happens, can i make the player who disconnected just run the code that knocks their items off and returns them?
yes
you get an event for a disconnect
they do, after all, really disconnect
they close their browser
since it's local multipaleyr from an engineering point of view, you don't really "lose" anything though
you can author a script that listens for these events and just, does whatever
and it will work for everybody
ill look into it in a bit, i dont want to learn a whole new thing and encounter whole new bugs as of now...
but if photon ends up still being buggy ill look into mana some more.
Solved it using AssetPostProcessor, no reason to use SG for it.
@chilly talon
Though I would agree this is probably not the best use case for SG
SG really shines when you need to dynamically generate code in real time while in the IDE, so you don’t need to keep going tabbing back and forth between Unity Editor and your IDE just to retrigger editor scripts.
In this case that’s not really being taken advantage of and the ease of editor scripts seems like the better choice to me.
hi there
does anyone know how to serialize objects in unity for webgl?
JsonSerializer.Serialize doesnt work on that platform
It can. What JSON serializer are you using?
the standard c#
System.Text.Json;
There can be IL2CPP considerations when it comes to this stuff, though I saw reports of it working
Switch to the newtonsoft json package to make sure IL2CPP is handled
Yeah STJ uses source generators, which might cause issues. But how did you get to use STJ in the first place, as far as I know Unity doesn't use .NET 5 or above
what are you trying to serialize
using system.text.json can add 10Mb or more to your webgl build
I tried this, somehow the entire scene turned pink as usual.
and gave the same errors that I posted before.
And then spams me with 'Allocation of 60 bytes at 00000208E3824210'
Maybe it's a terrible version of Unity.
Gonna check with 2021 LTS
Yup, seems like 2022 is just stupid, works in 2021 LTS.
How do I override this so that I dont have to change this origional code but make it compatable with hdrp?
basically I need to convert this:
RayTracingShader.SetMatrix("_CameraToWorld", _camera.cameraToWorldMatrix);
to this:
cmd.SetComputeMatrixParam(Shader, VariableName, Mat);
And I wanna do it by having a function called SetMatrix
is this possible?
Oh wow, good to know that’s the issue.
Not touching 2022 until much later then.
Yes, it is possible to create a function that sets a matrix parameter on a compute shader using the SetComputeMatrixParam method. Here is an example of how you could do this:
void SetMatrix(ComputeShader shader, string variableName, Matrix4x4 mat)
{
int kernelIndex = shader.FindKernel(kernelName);
shader.SetComputeMatrixParam(kernelIndex, variableName, mat);
}
You can then use this function like this:
SetMatrix(Shader, "VariableName", Mat);
This will set the matrix parameter VariableName on the compute shader Shader to the value of Mat.
That was generated by chat.openai.com
Let me know if it works!
but I wanna try and keep it as the old function call, wanna keep it as Shader.SetMatrix(VariableName, Mat);
Ask chat.openai.com, it’s brilliant, I can’t help any more sorry 😂
Just a heads up, rules were updated a few weeks ago, unverified AI-generated answers are not accepted here anymore
(Especially for advanced code, where research is more than expected)
ComputeShader doesn't even have method called SetComputeMatrixParam.
#📖┃code-of-conduct now includes:
Do not: Ask or answer questions using unverified AI-generated responses.
ChatGPT generated code is not brilliant, FYI
Sorry, ok, I’ll try and remember that in future
Guys does anyone know how i make the player look trough the right camera in photon pun ? he controlls his own character but looks trough the camera of another player
Where on earth is that code from? It is kind of a disaster.
Why are you using floats for the rows and columns? Do you intend to have fractional amounts?
Anyone here comfortable with Unity's Runtime Rigging, and has time to walk me through combining an animation with aiming?
(I've got it set up to IK the hand to aim at the target, but it "locks" the hand to the IK position & rotation.
I'd like to be able to turn/move the hands while keeping the movement/pose from the underlying animation.)
cam.enabled = photonView.isMine;
This is it
It should fix it
i forgot to update you i fixed it like 1hr ago but thank you
You're welcome 😁
i just destroy the other cameras to myself if they arent mine
Or just disable the camera component you might relay on camera for something so to avoid future errors disable the camera itself
Instead of destroying
I'm trying to get a rigged model of an arm to loosely follow the direction of the mouse all ragdoll like. I honestly don't even know where to start
Get an acceptable point using a raycast, and use IK to constrain the arm to that point
I have a first person multiplayer game. I want the player to be able to press buttons too while being able to move their character
How can I do that
When i try it the button is not responding at all
because unity is not considering that as a click
I believe I've solved this.
Anyone that wants to talk about the trickier edges of Animation Rigging is still very welcome/appreciated if you want to ping me 🙂
No good tutorials on the topic?
Hello, I have a bunch of images, which need to use the same effect. What is the best way to do this? I tried converting the sprites into a mesh and combining those into 1 main mesh and then putting the material I want for it on there, but I had problems with the size of the meshes. A problem with that is that the image count doesn't stay the same.
How this would work in game is that when it's your turn there's an outline effect over all cards (so the outline of the entire thing) and when you hover over a card only that card gets an outline.
This is what I get when I generate meshes from the sprites. It does generate them well, but I can't change the size
Hi, i have a map game and i want to paint the smaller divisions of the map in a color to represent countries. How do i do that without creating a new sprite for each smaller division of the map?
easiest way
make a list of a pixel point for each division, preferable as near to the center for each division.
then spiral out from that point until you hit a boundry.
once your spiral completes without changing anything your flood fill is complete for that division
do i use Texture2D.GetPixel or nah?
you should prepare the asset properly. it will take you much longer to program a solution. use the photoshop importer in unity. open the image in photoshop, use magic wand to select each province, then right click and Layer via Cut. name the layer the province. save as a psb (the modern psd format) directly into your assets folder. set up the importer. you now have each province as a sprite.
are you saying you want an outline effect? there are a lot of them in the asset store. you can also browse the render passes / render features github repos for examples of how to build this effect yourself. this includes an outline around the 2d area occluded by geometry.
#💻┃code-beginner was this code authored by a person?
does gimp work? i dont own photoshop and i am too lazy to pirate it
ty
unfortunately the way i always do this is #if UNITY_HDRP
if gimp can save to psb, yes. it probably can
it will work fine
there are maybe 60 provinces on screen. you can do this in 5 minutes
well it's not about the outline effect. I have a shader for that. My problem is that I want the outline to around all children and not around each child individually
yes, i'm saying there are outline effects that work on buffers like "the visible parts of just this geometry"
Thats only a part of the map
there are like
1000 provivces
ah okay, well I'll take a look for that then
then i guess it's going to take you 2h
i guarantee you still faster than programming a solution
try to get it to work with a few provinces
meaning try to cut out a few provinces
and have a working game first before you do the whole map
2 hours is nothing
you'll wanna use a more attractive map!!
don't actually use this one
i mean of course there are vector based maps that already have all the provinces separate @severe basin
and will look better
unity has an svg importer too
so it will generate sprites from a vector file
if you do the PSB approach, you have to treat it as a "sprite rig" so that it creates a prefab with everything laid out in the right place
i couldnt find a better map on Google so i used the victoria 2 province map
i will problably change it later tho
can i separate the provinces normally with a svg?
it would depend on on the svg is constructed
i would check shutterstock / pond5 for a pre-existing map
in vector format
and pay the $5 or whatever it is
the advantage of using a pre made map is that the borders are already laid out perfecly for the intended use
Heck ok thx
i know what you mean - i am confident you can find a vector version of every europa map
Hey I found weird stuff that my brain can't explain why this does happen.
Small back story:
I'm learning mesh rendering and using catlikecoding website for good tutorials. (<https://catlikecoding.com/unity/tutorials/procedural-meshes/square-grid/<link>)
I finished section #1.6. When I did press run I got this error: ArgumentException: Index buffer element #0 (value 1953066581) is out of bounds; mesh only has 4 vertices.
The value is insane. I played around and tried to fix it and stuff. Nothing that I found/test did work.
So I did add this:
Debug.Log($"Steam 0 stride {_mesh.GetVertexBufferStride(0)}");
Debug.Log($"Steam 1 stride {_mesh.GetVertexBufferStride(1)}");```
After this:
Mesh.MeshDataArray meshDataArray = Mesh.AllocateWritableMeshData(1);
Mesh.MeshData meshData = meshDataArray[0];```
It looks like this now:
private void GenerateMesh()
{
Mesh.MeshDataArray meshDataArray = Mesh.AllocateWritableMeshData(1);
Mesh.MeshData meshData = meshDataArray[0];
Debug.Log($"Steam 0 stride {_mesh.GetVertexBufferStride(0)}");
Debug.Log($"Steam 1 stride {_mesh.GetVertexBufferStride(1)}");
MeshJob<SquareGrid, SingleStream>.ScheduleParallel(
meshData, default
).Complete();
Mesh.ApplyAndDisposeWritableMeshData(meshDataArray, _mesh);
}```
and some how error is gone. Can somebody explain that insane index value is gone?
i think this is a red herring
what do you mean?
_mesh.GetVertexBufferStride(0) may have some side effects, but i don't think it does
the logs themselves have nothing to do with resolving the issue
i think you probably have a different issue
yeah that what I was thinking. I have no clue what is the problem tho.
It is just weird. I have followed that tutorial and checked everything like three times, but still getting this error.
Don't you actually just want to change the code in UpdateVisibilityOfObject?
Or rather
Call ChangeBool from GameObjectChanged instead of calling UpdateVisibilityOfObject
Or wait sorry
If you want to enable/disable the object... isn't the code correct already
I don't get what the issue is
It works but it isnt Server Sided
Only the client can see it
Can I run code in two different stages of the render stack? aka on two different events, I want something before rendering and another thing after rendering, for example if I put my code inside my renderer feature's Configure(), it doesn't work, however if I place it inside a method subscribed to RenderPipelineManager.beginCameraRendering, on a separate script, it does, however I'd like not to have a script separate from my renderer feature
Aka I want the same functionality of FrameRenderingStart and FrameRenderingEnd, together, inside a Custom Rendering Pass
possible?
You can enqueue more than one render pass in a single renderer feature, with different events
hello peeps, does anyone know how to optimize trees generation on terrain during runtime? I've tried to use threads, but most of the methods are only executable in the main thread
Okay that's actually smart, so I can basically implement the functionality of a script that has both framerenderingstart and framerenderingend together in one feature
Just have one pass queued with before rendering event and the other with after rendering, right?
Yep
But then how can I pass variables between the two? I have an offset that needs to be calculated in the first pass and passed to the second one, it can't be calculated in the second one since it would be 0 after rendering
How would you do it if these were separate scripts like you were thinking about doing before?
I have a variable declared offset that I can access in both events
Aka inside framerenderingstart and end
You could store it in a static field or give the "before pass" a reference to the "after pass" to set a field, or vice versa.
Or create a shared object that's given to both passes that they can access and modify
Hmm how would I go about the shared object method? Or can i access fields from the feature inside a pass?