#archived-code-advanced
1 messages · Page 46 of 1
I'm trying to do something similar to Render Scale option of URP to built-in rendering. Which :
- Render the cameras onto a render texture with 1/2 or 1/4 native size of screen.
- Render the result to the screen on real-time.
Set resolution works fine to reduce screen res, but it also reduces UI quality.
(1) is easy to work, but I'm struggling with (2), as I can't find or get the current Render Texture which Unity is using to draw onto the screen.
Does anyone face the same problem?
Today I saw some code like this
internal void InstantiateScoreFlyer(GUIFlyer scoreFlyerPrefab, int score)
{
if (!scoreFlyerPrefab) return;
if (!parentCanvas)
{
Debug.Log("no canvas");
GameObject gC = GameObject.Find("CanvasMain");
if (gC) parentCanvas = gC.GetComponent<Canvas>();
if (!parentCanvas) parentCanvas = FindObjectOfType<Canvas>();
}
GUIFlyer flyer = scoreFlyerPrefab.CreateFlyer(parentCanvas, score.ToString()); //Focus here
if (flyer)
{
flyer.transform.localScale = transform.lossyScale;
flyer.transform.position = RectTransformUtility.WorldToScreenPoint(Camera.main, transform.position);
}
}
Here scoreFlyerPrefab is a prefab thats dragged in the inspector. Surprising thing is it's calling CreatePrefab without even instantiating. This how CreateFlyer looks
public GUIFlyer CreateFlyer(Canvas parentCanvas, string flyerText)
{
if (!parentCanvas) return null;
GUIFlyer gF = Instantiate(this, parentCanvas.transform); //Focus here
if (gF && gF.text) gF.text.text = flyerText;
return gF;
}
Surprisingly, whole thing works without a problem. I understand that Instantiate will clone the object passed but here it's able construct the whole object by just passing "this" which means the GuiFlyer already got instantiated but more like an orphan copy (as there is no gameobject shown in scene hierarchy yet) and this whole thing is totally confusing.
Can someone explain how this whole thing works?
You can Instantiate from a component reference. It doesn't create an "orphan"
it copies the entire GameObject
(including all components, children etc)
and it just gives you back the reference to the component you copied on the new instance
it's the preferred way to Instantiate IMO because it skips unecessary GetComponent calls and GameObject referneces
^ this
Probably something is not clear from my question. Let me make it step wise
- Add a serializefield in a script to hold a prefab ([SerializeField] Gun m_gunPrefab)
- Drag a physical prefab asset to the above serialize field (m_gunPrefab)
- Hit play
- I can literally call methods with m_gunPrefab variable (without calling even Instantiate)
In step 4, if im able to call Gun methods, it actually means there is an instance of Gun already. But I don't see this component attached to any gameobject in scene hierarchy. Thats why im calling this orphan
Is Gun a monobehaviour in this example?
Also when you run the scene, search the hierarchy for t:Gun which should show every gameobject with Gun monobehaviour attached
Step 4 shouldn't work without having an active (in the scene) reference
Yes you are calling methods on the copy of the script that's on the prefab
it is not an "orphan"
but it does not exist in the scene yet. The prefab is there in its entirety
Just note that since it's a prefab and not in the scene, it will not have had its Awake, OnEnable, Start, etc. called on it. Also it will not Update etc..
Ah! Ok. Do you have reference about this to have a look. I thought something might have done internally but didn't have a solid proof as its a bit internal.
Can you please provide me some pointers on this?
THere's nothing to reference. It's just how it works
what do you want proof of?
So, it's created but not added to the scene. It may have got added to a gameObject too right? Just that it's not presented in the scene.
PRefabs are gameobjects by definition
They are just GameObjects as assets
about "the gameObject created but not added to the scene"
And they behave just like any other asset
that's the prefab
you can see it in your project folder
it's an asset
just like other assets (Materials, ScriptableObjects, Textures, etc..)
ok, thanks @sly grove
https://docs.unity3d.com/Manual/Prefabs.html
Unity’s Prefab system allows you to create, configure, and store a GameObject
complete with all its components, property values, and child GameObjects as a reusable Asset.
been moving things with asmdef and running into this, can't figure out which package I must add to the reference bucket of this asmdef: You must add a reference to assembly 'PackageTools, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
it's aron's Astar
Is there a Vector3.Slerp equivalent to Vector3.MoveTowards?
Verctor3.MoveTowards for spherical?
That would be just rotating the vector over time.
Yeah
Max deg rotation but i want it to use the vector length too
they are not normalized
i`m doing steering behaviour and i want to blend from current steering to desired steering
are the inputs from vector3.rotatetowards two rotation vevtors? normalized
They're direction vectors as explained in the description
And is there a vector3.rotatetowards for ecs? with float3
i found it probably
{
// replicates Unity Vector3.RotateTowards
float delta = Vector3.Angle(current, target) * Mathf.Deg2Rad;
float magDiff = target.magnitude - current.magnitude;
float sign = Mathf.Sign(magDiff);
float maxMagDelta = Mathf.Min(maxMagnitudeDelta, Mathf.Abs(magDiff));
float diff = Mathf.Min(1.0f, maxRadiansDelta / delta);
return Vector3.SlerpUnclamped(current.normalized, target.normalized, diff) *
(current.magnitude + maxMagDelta*sign);
}```
looks slow ..
You can rotate the direction with https://docs.unity3d.com/Packages/com.unity.mathematics@1.2/api/Unity.Mathematics.math.rotate.html#Unity_Mathematics_math_rotate_Unity_Mathematics_quaternion_Unity_Mathematics_float3_ And lerp the magnitude and it would be the same.
Hi everyone,
I'm running into a weird issue with Scriptable Object deserialization. I have scriptable objects which contain a simple custom class. This class has a bool array and a string array. The class is marked as Serializable, and both arrays are public. If I open the SO .asset files in a text editor, I can see the bool and string array data is serialized there. However, if I close and open the editor, the bool array data is appears as all false in Unity. It is seemingly not deserialized, because the .asset files still contain the original bool array data. The string array data is properly deserialized. If I change the name of the scriptable object in the editor, the original bool data appears.
Who knows what is happening here?
Using Unity 2019.4 btw
EDIT: solved! The problem was an OnValidate function which checked a non-serialized field which lead to the bool array being reset.
Hey guys, I am trying to run Code Coverage for my game however, it is stick on "Generating report" since 5 minutes. Could there be a reason behind this?
ZenjectException: Assert Hit! Could not find component with type 'MeshRenderer' on game object 'SceneContext'
at ModestTree.Assert.IsNotNull (System.Object val, System.String message, System.Object p1, System.Object p2) [0x00032] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Internal\Assert.cs:275
at Zenject.GetFromGameObjectGetterComponentProvider.GetAllInstancesWithInjectSplit (Zenject.InjectContext context, System.Collections.Generic.List`1[T] args, System.Action& injectAction, System.Collections.Generic.List`1[T] buffer) [0x0005b] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Providers\ComponentProviders\GetFromGameObjectGetterComponentProvider.cs:60
at Zenject.CachedProvider.GetAllInstancesWithInjectSplit (Zenject.InjectContext context, System.Collections.Generic.List`1[T] args, System.Action& injectAction, System.Collections.Generic.List`1[T] buffer) [0x00071] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Providers\CachedProvider.cs:100
at Zenject.IProviderExtensions.GetAllInstances (Zenject.IProvider creator, Zenject.InjectContext context, System.Collections.Generic.List`1[T] args, System.Collections.Generic.List`1[T] buffer) [0x00008] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Providers\IProviderExtensions.cs:31
at Zenject.IProviderExtensions.GetAllInstances (Zenject.IProvider creator, Zenject.InjectContext context, System.Collections.Generic.List`1[T] buffer) [0x00001] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Providers\IProviderExtensions.cs:22
at Zenject.DiContainer.GetDecoratedInstances (Zenject.IProvider provider, Zenject.InjectContext context, System.Collections.Generic.List`1[T] buffer) [0x0002b] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Main\DiContainer.cs:1199
at Zenject.DiContainer.SafeGetInstances (Zenject.DiContainer+ProviderInfo providerInfo, Zenject.InjectContext context, System.Collections.Generic.List`1[T] instances) [0x00094] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Main\DiContainer.cs:1128
at Zenject.DiContainer.ResolveDependencyRoots () [0x00113] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Main\DiContainer.cs:399
at Zenject.DiContainer.ResolveRoots () [0x00017] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Main\DiContainer.cs:333
at Zenject.SceneContext.Resolve () [0x00059] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\SceneContext.cs:299
at Zenject.SceneContext.RunInternal () [0x00016] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\SceneContext.cs:141
at Zenject.RunnableContext.Run () [0x00015] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\RunnableContext.cs:36
at Zenject.RunnableContext.Initialize () [0x00016] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\RunnableContext.cs:22
at Zenject.SceneContext.Awake () [0x00002] in D:\Praca\sowclean\Assets\Plugins\Zenject\Source\Install\Contexts\SceneContext.cs:113
(Filename: D:/Praca/sowclean/Assets/Plugins/Zenject/Source/Internal/Assert.cs Line: 275)
Getting this Zenject error
any ideas how to fix this monster?
for some reason it only happens in the build of my game
not in the editor
is there a way to replace the text of a function?
so if I have a property and function
public bool edible = true;
public void DoSomething(){
Debug.Log("eating");
}
in class "Fruit"
and I have
private Fruit apple;
can I do something like
apple.DoSomething = "Debug.Log("cutting");
like how I can do
apple.edible = false
basically is there a property that accesses the text of a function
No, but you probably want virtual methods instead
I know of virtual and asbtract methods but I'm not sure how I would use that for what I'm trying to do
ex. if it's a card game
every card in the deck is a blank "Card" class until attached with a specific "Card Name" card script that inherits from a parent "Card" class
would I be able to call the "Card Name" function from the parent "Card" class?
sorry if this is a basic C# concept I haven't worked with inheritance in a while
Don't hard code but rather use a variable: cs public void DoSomething(string something) { Debug.Log(something); }
this isn't what I'm trying to do
each function that replaces DoSomething would do something drastically different
completely different function bodies
I guess I should have gave a better example
public virtual void DoSoemthing()
{
Debug.Log("Do basic default stuff");
}```
If you have a base class Fruit, that has a method DoSomething, the default implementation can be Debug.Log("Eating") and then Apple will be it's own class and override DoSomething
yes but is there a way from the example I gave to call the child's method from the parent class
based on the child script that is attached
from this example
Overriding methods would change the behavior of the method regardless if on the parent or child.
Fruit appl = new Apple();
appl.DoSomething()
In this case DoSomething will do whatever Apple defined
hmm
so if I have
Parent: Fruit
Children: Apple, Pear, Orange
would I be able to do
Fruit.DoSomething
and call each of the children's DoSomething?
They're different instances so you'd have to keep a list
so I have a gameobject with Fruit Class
then I attach one of the three child scripts
This isn't an advance question. Should be further discussed in #💻┃code-beginner
What, no you attach the Apple class
now "DoSomething" would do something different based on what's attached
you haven't been able to answer it though
Because we're trying to fix your understanding of inheritance
You need to understand polymorphism for us to properly have a discussion...
no this is more hardcoding
it will depend on which child is attached
There's a lack of knowledge that's keeping the discussion from furthering.
I think it's misunderstanding not lack of knowledge
Inheritance is pretty straight forward.
What I'm asking is a practical use of it based on the situation I described though
The body of the base virtual/abstract method would be completely replaced by overriding method.
Plain and simple.
but that's calling the method from the child class
I'm talking about calling the method from the parent class
Doesn't matter, it's been replaced.
.
Overload and override are two different things. Should probably consider looking that up as well - overload would be what you're thinking about where behavior is relative to the current type.
You should read the whole section that is listed as Fundamentals.
you can make DoSomething a delegate and assign whatever behaviour you want to it from the outside
awesome this looks useful thank you
this is essentially functional programming, in that you are supplying partial implementation details in a different scope, potentially even injecting a closure over that scope.
class Foo
{
public Action DoSomething = () => Debug.Log("Foo"); // default behaviour
}
void SomehwereElse()
{
Foo instance = new();
instance.DoSomething = () => Debug.Log("Bar"); // assign a different behaviour
instance.DoSomething(); // invoke it
}
Note however that a delegate maintains a list of potentially multiple behaviours assigned to it and you'll have to be careful on managing what is registered into each one, making sure they don't refer to null objects.
How can I edit the properties of a .mat file from code ?
getting something odd with asmdef, scripts in my main assembly (no special folder and no asmdef) aren't getting access to hand-rolled asmdefs... am I reading the doc wrong? "Specify whether the predefined assemblies should reference this Project assembly."
Assembly-CSharp should automatically reference all assemblies that have that flag set to true. What platform settings do you have set on that assembly definition?
that's what i thought. that's the assembly scripts are put in when the script isn't in a special folder, right? - all platforms
asnap akayysnns HnnSNaPaPa nsnns
anyone found a way of using file-scoped namespaces in Unity?
Do you know good online references for unity game architectures ?
How exactly do anti-cheats work? Can't this just be reverse compiled and edited out of the application?
local anti cheats are most of the time ignored as it can be tampered with offline and all
what developers focus on, just as galaxyshard said, is making server anti cheat to protect other players
anything other than server anti cheat is most of the time a waste of time
and to answer your question on this, server version
it can include having a weak client "anti cheat" that basically verifies the player data before sending a request to the server
a legit player should only send requests of data is legit
you can then on the server compare the request with the player data and see if its correct
for example:
player wants to buy a new gun
it cost 25k
player has 2k
a cheater could have code rewritten and sends a request to fake it
verify on the server the player have enough money
if they dont, its most likely a cheater
done
It seems like every major game has a local anticheat running on the client
well most do now, i believe its a company (just assuming) that has made a fairly strong anti cheat and sells it to the game developers
but they do also include their own small anti cheat (again assuming)
Client side anti cheat is very effective at stopping 95% of the novices trying to follow some tutorials to cheat.
It won't stop the 5% that know what they are doing, but for the 95% that doesn't even know how to attach a debugger and just open Cheat Engine, it does extremely well.
Commercial anti cheat solutions stop even more of the 5%, but that's a hefty investment that's very likely not worth it.
is there any reason why switching on the deep profiler while a build is running (and restarting build) would cause a nullreferenceexception?
I can start something with the deep profiler on and it seems to work fine, and i can start profiling without it on, but when it gets switched on as something is running and rebuilds then issues start
i'm a beginner programmer so this prob sounds really dumb, but if someone is using speedhacks or something like that, can you just program a few conditions to check if those variables are within a normal range?
Sure, but then they can overwrite those checks
Not hard to introduce method detours and rewrite addresses of method calls
oh okay, I don't know how any of it works but I guess if you can overwrite code iniatially to cheat then you can probably also overwrite those checks
so i have this base Node class for a behaviour tree editor im making
[Serializable]
public class Node
{
public virtual void Run() { }
}
and i have other classes based on this class, including the InputNode, which is the opening node for a behaviour tree:
[Serializable]
public class InputNode : Node
{
public Node pass;
public override void Run()
{
if (pass != null)
pass.Run();
}
}
and the ActionNode, which contains a script that it will execute when run:
[Serializable]
public class ActionNode : Node
{
public Node pass;
public Action action;
public override void Run()
{
action.Execute();
if (pass != null)
pass.Run();
}
}
this is all in a scriptable object.
my problem is im trying to save an ActionNode (for example; could be any other type based on Node) to the pass variable in InputNode, but whenever i run the game the pass variable reverts to a Node type, even tho it was assigned with an ActionNode value. I've tested this in edit mode and it works fine, but i guess the data in the scriptable object is edited in some way so it doesnt save the different type. any way to get around this?
To serialize subclasses you need to use [SerializeReference]
Or, your nodes need to be UnityEngine.Object types in themselves (like ScriptableObject or MonoBehaviour)
do i put this above the class or the variable
Above the variable, it's like SerializeField
Except more complex, I would look at the !api
💻 Learn in detail about the scripting API that Unity provides https://docs.unity3d.com/ScriptReference/
it works, ty
Is using messages bad performance? 
My instincts say it has to be since it's using reflection, and has to scan thru every component... but colliders use messaging and don't seem to have a problem? 
I'm using events currently and it'd be real nice to decouple further
just say no to messages
bad for performance, bad for the soul
Well they did recently put out a new API to avoid that callback overhead, among several other issues 😛
The callbacks are relatively slow
@grim oxide Everything is bad for performance if not compared against anything. Performance considerations are also highly context dependent.
SendMessage doesn't actually use reflection, but it still does a lookup which is ofc. slower than a direct call or dereferenced one.
The bigger issue with SendMessage is how error prone it is - given that the name check only exists at runtime.
I'm trying to do myMeshCollider.GetVertices() but im getting a list of v3 like this:
[Log] (-3.20, 0.10, -3.20)
[Log] (-3.10, 0.10, -3.20)
[Log] (-3.20, 0.10, 3.20)
[Log] (-3.10, 0.10, 3.20)
[Log] (-3.20, 0.00, -3.20)
[Log] (3.20, 0.00, -3.20)
[Log] (-3.20, 0.00, 3.20)
[Log] (3.20, 0.00, 3.20)
[Log] (-3.20, 0.00, -3.20)
[Log] (3.20, 0.00, -3.20)
[Log] (-3.20, 0.10, -3.20)````
Does it make any sense?
all the coords of the vertices oscillate between -3.2 and 3.2 which is my world coord
but shouldnt the vertex of the mesh be in world pos ? i dont get it
Mesh.GetVertices is in local space
yeah im trying to do transform.TransformPoint(vertex)
as suggested here:
finnally i could
isnt it InvereTransform to go local=>world?
could be wrong tho, its stated in the docu
I have the weirdest error. I have a IDialogue Script which is called when the player interacts with the gameObject that has the script. It then calls the dialogue manager and passes the dialogue and object info so it can display it on the screen. It works fine on debug mode, but when I build it with more than 1 dialogue gameObject, it always shows the newest dialogue even if i interact with an object on the other side of the map.
Its really confusing me lol
and knowing me its a stupid mistake i keep looking over
This is the interact code
protected override void OnCollide(Collider2D collider) {
if (Input.GetButtonDown("Interact"))
{
FindObjectOfType<DialogueManager>().StartDialogue(this);
}
else base.OnCollide(collider);
}
And this is the StartDialogue code
public void StartDialogue(IDialogue dialogue)
{
this.dialogue = dialogue;
npcName.text = dialogue.npcName;
dialogueBox.SetActive(true);
sentences.Clear();
foreach (string sentence in dialogue.dialogue)
{
sentences.Enqueue(sentence);
}
DisplayNextSentence();
}
ooh i just realised its detecting the collision everywhere on the map because it was colliding with the wall collider
sorry for the spam
hi guys,
a question regarding DOTS:
Why does the Random here get the same seed for every job? The System exists once and Jobs are newly created objects, so
shouldn't each object creation get a new random value?
var rndSeed = SystemAPI.GetSingletonRW<RandomValue>();
var jh = new SpawnJob {
buffer = cmdBuffer,
deltaTime = deltaTime,
// not sure why, but this still generates all jobs with same seed
rndSeed = rndSeed.ValueRW.value.NextUInt()
}.Schedule(state.Dependency);
jh.Complete();
i get a new seed/value for every frame but all Spawnjobs within the same frame get the same seed
hmm you are passing in the rndSeed to the job, and every execute() call reuses that same seed
would have to see more of the implementation but thats a really common thing, you want a different Random instance for each one
what do you need more of the implementation?
it is very basic. if my reference is wrong and Random.value actually gets copied, then all frames should have the same seed
thats not happening, they are changing, so next() is correctly called on the random object
but how can Next() be called multiple times without increaseing the seed for each call?
obviously thats not possible
so it means the job object gets copied(?) for execution?
its the only explanation i have
here is the job:
[BurstCompile]
public partial struct SpawnJob : IJobEntity
{
public float deltaTime;
public EntityCommandBuffer.ParallelWriter buffer;
public uint rndSeed;
[BurstCompile]
public void Execute(RefRW<SpawnZone> spawnZone, TransformAspect tf, PostTransformScale scale) {
spawnZone.ValueRW.elapsedTime += deltaTime;
if (spawnZone.ValueRW.elapsedTime >= spawnZone.ValueRW.SpawnTimer) {
spawnZone.ValueRW.elapsedTime -= spawnZone.ValueRW.SpawnTimer;
var rnd = new Random(rndSeed);
// calculate random spawn position in spawn Zone
var x_max = tf.LocalPosition.x + (scale.Value.c0.x / 2);
var x_min = tf.LocalPosition.x - (scale.Value.c0.x / 2);
var z_max = tf.LocalPosition.z + (scale.Value.c2.z / 2);
var z_min = tf.LocalPosition.z - (scale.Value.c2.z / 2);
var x = rnd.NextFloat(x_min, x_max);
var z = rnd.NextFloat(z_min, z_max);
var spawnedEntity = buffer.Instantiate(0, spawnZone.ValueRW.UnitPrefab);
buffer.SetComponent(1, spawnedEntity, new LocalTransform {
Position = new float3(x, 1, z),
Scale = 1,
});
}
}
}
yes so you are passing in a random seed to the job object, and every time the Execute function is called it creates a new random using the same seed
so new Random(2) -> next() function will always give the same value
because the seed is deterministic
yes, but the Job object itself should get a differnet seed for each instantiation
there is one job and many executions i think
so the new Job() part only gets called once
ah, the execute function itself is what gets called x times, not the job
thats it
well, then the only solution would be having a random object inside the SpawnZone component
for next time, we actually use this channel for dots questions
https://discord.com/channels/489222168727519232/1064581837055348857
more people who use dots in there
not that it was wrong to post here
ok, will post there next time thy
yeah i have a test project with 100,000 units that wander to random destinations and each unit has their own Random component lol
but to add to this, if i would create spawZones in a job, i would have the same problem, not being able to init a Spawnzone with a different random value
i know no way of getting different random values into the execute then
each spawn zone has a RandomComponent : ComponentData with a mathematics.Random instance in it
and the job accesses 'SpawnZoneAspect', the aspect has RW access to the random component
that way all the spawn zones can generate random numbers without waiting for the Random instance to be free
yes but that only works if you create the SpawnZone not in a parallel job itself
otherwise you cannot create differnet seeds for each spawnZone
true, but how many spawners do you really need?
is there no way of accessing static variables with mutexes out of execute?
is it not ok to do it once on the main thread at the start of the program?
its not about the actual spawner, its more about the concept
there would have to be an original spawner to spawn the spawn zones, and that original spawner would have the original seed made on the main thread i guess
and from there the seeds branch out into a tree graph i guess haha
yes, but the problem still persists... having many random values in parallel requires setting them up in a non-paralel way beforehand. Normally i would access a mutexed static variable,
but i'm not sure if unity even supports mutexes
thanks for your input
i think there's a method where you can count the possible number of threads and have an array of Random instances, and then inside the job you access the Random instance using the currentThreadID
i havent tried it and don't know how safe it is lol
yeah i read it somewhere, i think the BatchEntity job provides access to some index, but i didnt spend more time investigating, as it comes with a whole lot of other strings attached
Is there a message I have to send from a TCPListener -> TCPClient to tell the client it's finished connecting? I have a client that can connect to an existing service and works fine, but when I have a server on my localhost the server fires the BeginAcceptTcpClient callback, calls EndAcceptTcpClient, and says the client is connected and the networkstream is readable, but the client never fires the on-connected event
no idea about TCP-APi, but OnConnected sounds more like a server side event, rather then a client side event. menaing maybe its only fired on the server once a new client connected
Client.BeginConnect(Dns.GetHostAddresses(ServerAddress), ServerPort, new AsyncCallback(onConnect), Client);
``` The client fires the callback when it gets some sort of connection confirmation, and that callback starts the stream reading thread while also sending the first packet to the server. This works fine for the existing server that isn't under my control
When I try to connect to my localhost server, that callback never fires but the server-side says it made a connection which is why I'm a bit lost lol
How does the StringLogger sink work? How do I access the in-memory string?
Nevermind, you can just read it from the sink
but how can Next() be called multiple times without increaseing the seed for each call?
doesNextUInt()mutateRandomValuein the peculiar way you have wrapped it? it clearly doesn't. the job construction is a red herring.
i assume your'e spawning more than one job, and with distinct values right?
there's a lot of mental noise around hwat's really going on. to put it simply
@hybrid notch
[1]
var seedGenerator = new System.Random();
foreach (var jobSpec in jobSpecs) {
var job = new Job(jobSpec, new Random(seedGenerator.NextInt()));
}
is correct.
var seedGenerator = new System.Random();
var seed = seedGenerator.NextInt();
foreach (var jobSpec in jobSpecs) {
var job = new Job(jobSpec, new Random(seed));
}
is not.
[2] also, you should know, that your random implementation may be of the form
class Random {
int seed;
int NextMutable() {
seed = XORShift(seed);
return seed;
}
}
let's pretend int XORShift(seed) => seed + 1;. it sort of is, essentially. then clearly a lot of your spawned sequences, in your current code, will be exactly the same
since your code is incomplete it's hard to say what exactly your bug is, but it's 70% likely to be [2] and 30% likely to be [1]
what is your objective?
stringlogger sink?
Unity.Logging
gotchya... what is your goal btw?
Wanting to set up a more extensive logging setup
it has similar performance to any other dependency injection system
you can always import microsoft logging
and use standard .net ecosystem tools
Those aren't burst compatible
why would you need to burst compile a job that prints logs
Because I want to log from inside burst compiled jobs
👀👀👀👀👀👀👀
why not not burst compile them
if you need logging
The microsoft logging libraries will not work in burst
I don't want to turn off burst
I can, with the logging library
with whose logging library?
Unity's
It most likely won't work with microsofts
Just general logging stuff?
logging from a burst compiled job... you could easily wind up with logging taking 10,000x longer than the job itself
it's not like unity's implementation is any good
alright well i'm sure it'll make sense
It's probably as fast as it can be
tbh it's less about jobs and just systems where speed is less important, but those are all usually burst compiled as well now
There is a game server I already have a working connection and functionality to use with it for non-malicious reasons that even the CEO is aware of (or was, probably doesn't remember who I am by now). Instead of now using the actual game server, I want to emulate my own to a much more limited extent just for my own usage
okay, so your question is, how do i communicate with a game server backend i have no control over?
which game is it?
The client initiates contact, and when that callback on connect fires it sends the first higher level packet of info to start the login process
based on the one line of code you shared, you are still at the beginning of a long journey
it is hard to say
But on my own barebones server, the client doesn't get that invisible go ahead even though the server accepts the connection
i see. so you're asking, "how to i author a correctly working tcp server in c#?"
The client is basically finished and I can even use it on my phone
what is the type of Client in your snippet?
Tcpclient, though I also refer to the whole program that I can run, log into the game, and message people with
okay
https://github.com/davidfowl/MultiProtocolAspNetCore this is a very robust way to create a tcp-based server using c#
The client is ready to go, but my attempt at the server can't get the tcpclient on the client program to fire the on connect callback even though the server accepts the connection and is waiting to read data from the stream
this is an example of a feature already in aspnet core
are you authoring your server in c#?
Yes
don't get hung up on this on connect callback stuff or wahtever
your server isn't written correctly
we don't have to investigate that
as soon as you said you create the threads, you're taking a bad approach anyway
the thing i link is just a sample
showing how easy it is to set up a tcp server that is "enterprise grade" so to speak
your client looks dubious too, but that's okay
if it works it works
I'll take a look, I use a thread so I don't need to use async and lock up the main unity thread waiting to read
There's ton of multiplayer solution and package that helps solve this TCP problem for you. Under the hood, you are basically receiving packet signal from the internet, and properly deserialize bytes of data into recognizable information you can use in your code.
wait
are you saying the server runsi n th esame process as yoru game?
No, separate process
(not too uncommon with "playing" hosts though)
namespace KestrelTcpDemo
{
public class MyEchoConnectionHandler : ConnectionHandler
{
private readonly ILogger<MyEchoConnectionHandler> _logger;
public MyEchoConnectionHandler(ILogger<MyEchoConnectionHandler> logger)
{
_logger = logger;
}
public override async Task OnConnectedAsync(ConnectionContext connection)
{
_logger.LogInformation(connection.ConnectionId + " connected");
while (true)
{
var result = await connection.Transport.Input.ReadAsync();
var buffer = result.Buffer;
foreach (var segment in buffer)
{
await connection.Transport.Output.WriteAsync(segment);
}
if (result.IsCompleted)
{
break;
}
connection.Transport.Input.AdvanceTo(buffer.End);
}
_logger.LogInformation(connection.ConnectionId + " disconnected");
}
}
}
I built the client and then run the server in unity for easier debugging
@sage glen do you see what's going on here?
okay
so IS IT a separate process, or is it NOT a separate process?
you say run the server in unity
i wouldn't use that expression for thes ame process
do you mean you new Process() in unity, an executable you built elsewhere?
The client works in the editor or as a standalone build on pc and on my phone I'm using now
Yeah I'll check out the example l, there's probably a single thing I'm missing. Thank you 
the exampel will look 100% different than what you have now
none of it will transfer
Yeah async
but on the other hand, it will work 100% more lol
not just async
it isn't the async part that's essential
it's just... totally different conceptually
from a way you organize your code
to what you are concretely doing
anyway, if you told me what game it is, i could be more helpful
I went with tcplistener since tcpclient worked for the actual game server
but you didn't. it's not sensitive
Apb reloaded
okay
https://media.discordapp.net/attachments/167252659428917248/1078935040303562792/Screenshot_20230225-010118.png my phone edition of the client that works with the actual games server
All good, appreciate the help already 
Does anyone have a trick for counting main thread allocations without resorting to the full-blown profiler window? I'd love to be able to directly instrument my code with a couple extra lines and ask "between point A and point B, how many allocations (and how many bytes) were allocated on the main thread?"
You could even imagine wrapping this in a unit test and saying "calling this function shouldn't allocate".
Looks like TestFramework has some sample code that can do this, so I extracted it into something slightly more generic here:
https://gist.github.com/jeffomatic/cfa560bad7a1163730d1b5f75f549f93
I'm getting the following crash report. I can't tell what the actual cause it. Is it FMOD or VFX? There seem to be a number of similar posts online but none seem quite right. Running 2022.2.8f1 but it was happening on older versions too.
See thread for stack trace.
Does anyone have any idea why my raycast appears to be hitting an object that is on an ignored layer? The lasers are all on the Laser layer.
Physics.Raycast(transform.position, player.transform.position - transform.position, out RaycastHit hit, myMask);
Gizmos.DrawLine(transform.position, hit.point);
what the myMasks value
um hang on, unity just crashed lol
Make sure that its a LayerMask not a Layer
errrm what he mean is that, is myMask is a Laser? or Player or Interacble
The first screenshot shows the selected values for myMask
Here is the full list
Here are the values for each layer
Are you saying that the ray is hitting the Laser layer?
It looks like it
get the hit collider to make sure, you can access its layer
Confirm with debug.log
bc the mask doesnt include the layer 9 afai can tell
print("Hit object: " + hit.collider.gameObject.name + "\thit layer: " + hit.collider.gameObject.layer.ToString());
Result
Hit object: Detection Laser (5) hit layer: 9
wdym? The layer I want ignored should be unchecked in editor right?
Hello?
Did everybody that was helping me just happen to log off at the same time?
Or is it just that nobody has a clue what is wrong with my thing?
Seems odd, are you sure you're checking the correct Turret object?
sry yeah i went off. everything looks okay so far. layermask seems to exclude the actual layer of the hit object, but its still the most likely point of failure
There are other turrets in the scene, but they have a range that doesn't reach the player at this point. I can disable all but this one and check again.
Yep, same result.
at this point i would write assertions
Log the object that hit with this result, click on the log to find it in the scene.
I mean something like
Debug.Log("My layer mask " + gameObject.layer, gameObject);
So he can confirm he's looking at the correct objects mask.
It hits two different lasers because they move back and forth but it's the ones I expect.
I had to modify your print to make it print the right things but I think it's doing what you wanted.
Debug.Log("My layer mask " + hit.collider.gameObject.layer, hit.collider.gameObject);
And inspecting those lasers mask also does not have the 9th layer of Laser selected?
yes
No I mean their "myMask" variable.
Lasers don't have a myMask. Turrets have a myMask.
Turrets are the ones doing the raycast.
My bad, your log should not log the thing they hit, but the object that is checking.
oh
Debug.Log("My layer mask " + hit.collider.gameObject.layer, gameObject);
If they do, I would restart unity, and if that doesn't work redo their mask (set to everything, and then uncheck etc) 😅
I've restarted already. I started having this issue two days ago and have rerun it multiple times. It actually crashed an hour ago too after I started asking for help here lol. I'll try reselecting the layers tho.
It's acting like the laser is on every layer greater than water.
I unchecked everything and most of them it shows not hitting anything, but if any individual layer from 4+ it shows it is hitting the laser.
Hey guys asked this question in beginner and general. Dont seem to be a response for it maybe someone here knows.
UnityEditor has the following functions to get and modify the animation curves
- AnimationUtility.GetCurveBindings, AnimationUtility.GetEditorCurve
- AnimationUtility.SetEditorCurves
Now my animations are all generated ondemand, in runtime because my characters have interchangeable body parts and rig.
I noticed there is no way in UnityEngine to:
- Get animation curves for a clip
- Set curves in bulk instead have to use a function called
clip.SetCurvewhich does it singly and is REALLY slow....
Does anyone have any solution to getting animation curves for a clip without UnityEditor?
Does anyone have any solution for setting curves in bulk without UnityEditor?
Mostly the people who answer questions here are also perusing the other channels too.
in light of the fact that the masked setting on TMP text is known to be bugged and busted
is there a known work around?
Does anyone have any solution to getting animation curves for a clip without UnityEditor?
Does anyone have any solution for setting curves in bulk without UnityEditor
you can directly write the data to the text asset files (the prefab / scene)
what is your objective?
you can also look at how the various model importers generate animation data. you are not familiar yet with the whole API
you can definitely create keyframe data "in bulk"
In my case writing the data straight to a text file from editor isn't viable enough of a solution for me. As there can be a huge combination of animations which can be created from different body parts. I've put a image of the various unique models i have then the second image has these body parts combined randomly. Each 20 of the unique models on the left have base animations .e.g. Idle, Walk etc.....
When a combination of these meshes and rigs are combined, the relevant keyframe data from each animation needs to be copied and a new animation is made. If there are 8 body parts in the system there can be a possible of 8^N animations, not viable really for me to use text assets
The next best option i have is to dockerise unity editor and generate these animations in the cloud which i dont really want to do
:S
without the editor i dont see a method for this
My code works fine until i try to build then it throws Unity editor methods cannot find 😦
The next best option i have is to dockerise unity editor and generate these animations in the cloud which i dont really want to do
what is your goal?
what is the idea*
are you trying to use unity to generate video assets?
So based on the combination of the meshes i have in the model i want to generate a new animation on runtime for .e.g. idle
This is for a game, so the end product is webgl, exe, osx executable
okay
Now my animations are all generated ondemand, in runtime because my characters have interchangeable body parts and rig.
what do you mean? are you saying you're generating keyframes for bones procedurally?
it looks like you have generated the models procedurally. however, they appear to be roughly the same size
So yeah each of these models have animations.
.e.g. Idle, Run, Walk
Now i can mix and match these models....
.e.g. i make a new model with
- Kitsune Head
- Lucky 777 Body
Now what the code does is it gets the animation keyframes to copy from the Kitsune Idle animation (Head keyframes only) and Lucky 777 Idle animation (Body keyframes only) and makes a new animation and attaches it to the animation override controller
it looks like they should all have the same avatar?
why are you copying animation keyframes
because the idle animations are unique for each kitsu
and it was made by a game studio to be like this
i am missing a lot of context here to be helpful
So they can interchange parts
this isn't going to be one of those things where there's just some api you're not aware of
the thing you're doing right now doesn't make sense
I guess im not explaining it good enough
no
i understand what you are trying to do
your approach sounds really bad
and the more i learn, the worse it sounds lol
How do you think i should do it without creating a new animation 😐
all of these characters are roughly the same. you can treat each customizable limb/body part/whatever as its own skinned mesh, bound to a single unified avatar
hmm interesting
it doesn't matter if each kitsune has its own idle animation
you would have 100x idle animation clips, sure, that's fine, they're all animated against the same skeleton
then you guys made a colossal error nothing bad has happened yet*
Stuff like the head, ears, wings, tails are not shared
well
there's lots of runtime retargeting approaches, specifically for this use case
but it's not really different
the skeletons can be slightly different sizes, and everythying will just work
your unified avatar should always have wing bones, regardless of the customized model. you don't HAVE to show the wing mesh
if there is really a one-off bone, like a specific tail, then that's duplicated out and treated separately
but the same concept applies
hmm interesting so i would put all possible bones inside the unified avatar
you can do whatever makes sense to you
and only display a few
the purpose of the avatar idea is to enable retargeting like this
i think you might want a more comprehensive tutorial
i don't know a lot about this either unfortunately
not aware of the full systems yet
@regal olive so to clarify, try to share as much skeleton as possible. for unshared stuff, make a new skeleton and avatar
mix and match skinnedmeshrenderer (i.e. body plan pieces). you will want to animate each piece against that skeleton. so you can imagine an arm just attached to that one skeleton
the whole skeleton hierarchy with the 1 body part geometry
the avatar describes how to interpret your 3d modeler bone hierarchy. it isn't that important / special in and of itself
Thanks will do ❤️
i think you're way closer to a working thing that you think you are
you're maybe a day or two away from having htis all work @regal olive
once you start to comprehend the meaning of all this animation rigging stuff
it will go fast
nice hopefully a quick one i've done this multiple times just not in unity
how can I prevent my graph view from clearing when I enter play mode
Hey all, I have a question regarding running post processing during runtime
I have assetbundled some a bloom fx and I'm trying to use it in a game
I run the code
var pap = GameCameras.instance.mainCamera.GetUniversalAdditionalCameraData();
GameCameras.instance.mainCamera.GetUniversalAdditionalCameraData().renderPostProcessing = true;
var a = flowers.GetComponent<Volume>();
a.enabled = true;
var cs = a.profile.components;
Log($"length is {cs.Count}"); // length is 1
Log($"CS is {cs[0].name}"); // name is Bloom (clone)
Log($"Was able to get {a.profile.TryGet(out Bloom b)}"); // prints true
b.active = true;
b.threshold.value = 1f;
b.intensity.value = 1000f;
I get no errors but the object I wish to glow does nothing
This is unity 2020.2.2 if that matters
does the object output a bright enough color to bloom
it's white
then it wont bloom that much
It blooms in the unity editor, but stops blooming in-game
ah
does it bloom in editor Game Preview
and then stop blooming when you enter play mode
or is it never blooming
Errr, it stops blooming when I instantiate the object from the assetbundle in the real game.
Now that I think about it, could it be because in the built version of the game, this isn't set?
If so, is there a way to set it outside of the editor?
can you have an event called from 2 different classes (same event name) so that the listeners can be called from either class?
if you use URP shaders and the asset is not set everything would turn pink
so if that is not an issue then the asset is working as intended
Hmm then why else could it be doing nothing in the actual game. The sprite looks just fine except it doesn't bloom. And there are no errors.
No... not really. Events are made to be "secure" by making so only the class that owns / creates it can invoke it!
you could go around that by using (maybe) reflection or inheratance
but could you create an event with the same name in another class
oh yeah
Could there be another setting for the camera I need to set besides renderPostProcessing?
The camera was part of the original scene, I'm not bringing the camera from my unity project in with the assetbundle into the actual game.
Is there any reason why the volume needs to be in the asset bundle and not in the scene with the camera
It's because I'm modding a game.
No, I had to get the dll from a fake unity project I built. It doesn't give any errors when I use the URP functions so I assume I referenced the correct stuff.
oh boi
if the game uses buildt in RP the shaders will be incompatible with URP ones
so if you do change the asset as you wanted the whole game would turn pink
@old swallow i think i found a way to do it without duplicate events. Thanks for the help though!
hmm, I'm actually trying to add bloom to a new asset, not one that's already in the game
but I guess the bloom affects in-game assets to so your point stands
is there a reason why it's not even turning pink rn?
what shader does the new asset use
Sprites-Default
and full path?
Sprites/Default
the one that comes with unity
yeah ok so that shader is compatable with both Buildt in RP and Universal RP
but it was made for Buildt in RP
that is why nothing is ping in the game and editor
now the code you add (the volume stuff) is cind of just doing nothing
you add the components and change values
but at the end of the day URP volume just checks if the render pipeline is set to URP and if not (witch happens in the game) just does nothing
if you would force the game to use URP everything would turn pink because most Buildt in shaders dont work with URP
Ah so something like the code here won't work :/
https://docs.unity3d.com/Manual/srp-setting-render-pipeline-asset.html
Do I have any options?
it would work, it would change the render pipeline, but I dont think you would like the outcome (pink world unless you change every shader in the game)
Could I use the Post Processing package instead?
Ah well that's a relief I can try that.
if we are talking about the same one that is
my only problem with that package is that I can't get it to only affect one object
at the end of the day you should have your modding environment the exact same as the game
I make a layer for the bloom fx and add a Post-process layer component to the camera (this is all in the editor so far not the real game), and set the layer. And yet all the sprites, even the ones that dont use that layer still bloom.
Err but that goes outside this question. Anyways, thank you so much for the help, that cleared up a lot.
If I have questions on how to use the post processing package so it doesn't affect every object, should I ask here or #archived-code-general ?
#💥┃post-processing actually
oh 🥴
thank you
but I will say that most ppl there are using URP PP now
might be tough to get an answer
It doesn't seem like I have much of a choice unless I change every shader, do I?
yup
and honestly if this is a 2D game I would just add the bloom effect in photoshop
would help performance too
If I want a bloom effect that flashes, could that also be done with static sprites?
Well I guess it has to because that's what the base game does.
We did this by pushing HDR brightness beyond 1f
You can set your bloom threshold so that only things with brightness greater than Color.white bloom
And then push various colors beyond that to make them glow
Unfortunately it seems like I cant even get the post processing package to work.
When I add the Post-processing layer to the main camera, the following error gets spammed
[ERROR]:[UNITY] - NullReferenceException: Object reference not set to an instance of an object
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.AmbientOcclusion.IsEnabledAndSupported (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.PostProcessLayer.SetLegacyCameraFlags (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.PostProcessLayer.SetupContext (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.PostProcessLayer.BuildCommandBuffers () (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
[ERROR]:[UNITY] - UnityEngine.Rendering.PostProcessing.PostProcessLayer.OnPreCull () (at <a6f755e7caf0432c88099cb80bdfd2b0>:0)
This happens when I run GameCameras.instance.mainCamera.gameObject.AddComponent<PostProcessLayer>().volumeLayer = 31;
ooo cool idea
ask in #💥┃post-processing probably
alrighty
my people
what counts as an advanced coding concept? /gen
just my 2 cents, but:
in the context of this thread, I'd say just about anything that can't be reasonably googled or stepped through (or understood by someone with little experience). any question that is relatively common or has a google-able answer (i.e. "GetComponent is null!!!! why???") would be very much beginner
:3
ty for an honest answer
in general coding, it really does just depend on experience - i know devs who would call a concept advanced, whereas others who have been working for 20+ years would laugh at it
that's kind of the curse of being a human - everything seems advanced when you're learning, but everything seems beginner once you know (see: dunning-kruger)
:3
thank you very much
is there something in particular you had in mind?
I was afraid that any questions I had for here would be looked down upon from mount olympus lol 
yes
it can't hurt to ask. people don't bite if they know you have done your due diligence. the only time you'll get that sort of attitude is if you're asking something that takes someone 2 seconds to answer and involves them writing your exact q on google
I'm trying to refactor my code with the SOLID principles (trying to learn them at the same time, really I have no idea if I'm doing it right or not)
and I have this class that I want to be able to manage the selectable card objects on my screen by triggering their behaviors and stuff
but, I want to know where I should draw the line with how much complexity to allow in my selection logic class (because of single responsibility)
you've kind of answered it yourself - you should draw the line when your class no longer serves it's single responsibility. i'd suggest posting your code and explaining where exactly you're considering splitting out the logic
it's v late for myself but if it goes unanswered i'll take a look tomoz
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelectionLogic : MonoBehaviour
{
private bool _selected; // whether selection behavior is currently active
private Collider2D _currentHover; // current object under the mouse
private Collider2D _lastHover; // last object under the mouse
void Update()
{
if (_selected)
{
if (Input.GetMouseButtonDown(0))
{
// Initiate DE-selection behavior
}
}
else
{
_currentHover = MyNamespace.Selector.UnderMouse(); // gets the highest-rendered object under the mouse
if (_currentHover)
{
if (!_lastHover || _lastHover != _currentHover)
// Check if there was no last object or the object under the mouse is new
{
// Initiate hovering pre-selection behavior
}
if (Input.GetMouseButtonDown(0))
{
// Initiate selection behavior
}
}
else
{
_lastHover = null; // "Forget" _lastHover if the mouse starts hovering over nothing
}
}
}
}
(I've removed all the technical stuff to focus mostly on the logic for this question)
I just want to know, is this too much to be considered a single responsibility?
or is it fine?
only had a quick glance but first thought is that SelectionLogic is a poor name - avoid things like __Logic, because it doesn't actually describe what you want the class to do. a good step to take especially when considering a class's responsibility is to find an apt name - it'll help you imagine the bounds of what the class is meant to do
(I changed the name of the class for the question as well, my apologies)
what was it named before?
original spaghetti code was named ToggleFollow
newest iteration is named SelectionManager which I realize isn't much better
hmm
i don't see an issue, but with most of the code stripped out it's hard to say; all it's doing at the moment is reading inputs, which isn't unreasonable. an argument could be made that you should keep everything that registers inputs separate from classes that actually do stuff - so you could always separate things out that way
anyway, nothing too crazy going on here, it's not a monolith. i wouldn't worry so much about whether or not it's perfectly SOLID, it's not bad

Thamk you
The reason I wanted to build this separately is because it's actually triggering events and stuff
But thank you for your time
public IEnumerator AnimateBubbleText()
{
//text alpha starts at 0
for (int i = 0; i < mainText.Length; i++)
{
//make i'th character alpha 255
textComponent.ForceMeshUpdate();
TMP_TextInfo textInfo = textComponent.textInfo;
int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;
int vertexIndex = textInfo.characterInfo[i].vertexIndex;
Color32[] vertexColors = textInfo.meshInfo[materialIndex].colors32;
vertexColors[vertexIndex + 0].a = 255;
vertexColors[vertexIndex + 1].a = 255;
vertexColors[vertexIndex + 2].a = 255;
vertexColors[vertexIndex + 3].a = 255;
textComponent.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32);
yield return new WaitForSecondsRealtime(0.05f);
}
}
Can anyone help me figure out why this code produces this behavior? It's supposed to updated the alpha of each character to 255 and keep it that way.
I have a serialized custom Action class (in a separate namespace so it doesn't cause problems with the built in action class) in a scriptable object and I'm trying to assign a value with a type of TestAction : Action. the variable is using [SerializeReference] but when I try to assign it it says theres type mismatch in the inspector. I'm doing a similar thing in a list (of a custom class which includes the same kind of serialized variable) and it seems to work fine, but outside a list it doesn't seem to work right. the value also doesn't seem to be showing up at all in the inspector (only variables in the base class) but it seems to be working fine otherwise so ig something about that is getting around the type mismatch problem
sorry if that wasn't very clear, im typing on my phone which isn't very good for long paragraphs like this when i can only see like 2 words at a time
what is the idea
what are you trying to do
you can look at textmeshpro's source code, it is open. i guess force mesh update resets all the vertx colors back to 0 (i.e., what you set in the inspector)
use event system
class SelectionLogic : Unity.UI.Selectable {
public bool selected => EventSystem.current.currentSelectedGameObject == this.gameObject;
}
I don't know how those work yet, I'm working on implementing actual C# events but I'll enlighten myself with google soon I'm sure enough
okay, googled it, not really interested in using something 40x slower that basically just serializes an event in the editor
humble me if you wish
I'm having an issue where particle effects are waiting until they are on-screen to fire and a ton of them are building up and crashing my game. Does anyone know if there's a setting to fix this?
it sounds like you googled Unity Event rather than EventSystem
Why doesn't the UnityEditorConsole sink respect output formatting 
I'm trying to copy a material that uses compute buffers but it looks like when I call 'instantiate' on a material, it seem to mess up the compute buffer internal stuff somehow. On the mac it gives an error relating to these computer buffers (I don't have the exact error to hand), on the PC it gives no error but also fails to render.
does anybody know if there are issues with the shader/computer buffer interface ?
The mac error is 'requires a ComputeBuffer at index 4 to be bound, but none provided'
note that this works fine on a material created as an asset but if I try to create a material at runtime, it fails in this way.
Culling Mode Choose whether to pause Particle System simulation when particles are offscreen. Culling when offscreen is most efficient, but you may want to continue simulation for off-one effects.
what are you trying to do?
"i want to use bloom in a 2d sprite game" ? for now, try creating a new scene, and right there in the editor, figure out how to show bloom the way you want first
using the postprocessing volumes in the scene, without code
I have that already
okay
@undone coral i explained it a little more here, this was when i was trying to get it working on the list. now it's the same thing outside of the list and something isn't working
and you're asking how you programmatically turn bloom on and off?
don't tell me the bug in your implementation
it's bad
we're going to get rid of it
tell me what you're trying to do @tender scaffold
what is your goal?
don't program in the inspector
there's no such thing as a serializable action
remove serializable, remove your scriptable objects. if you want to declare a behavior tree, for now, try to do it in code. here is an example:
class BehaviorTreeDefintions {
public static BehaviorTree Patrol(Vector3[] positions, float speed) {
var bt = new BehaviorTree();
bt.AddState(new State() { ... });
...
return bt;
}
}
you will have like 20 of these max, and the thing you will not be editing is the actual code. you're going to be making changes to the paramters like positions and speed.
you don't want to program in the inspector anyway
you can make those changes in the editor
-im not using unitys actions, this is a different namespace
-im not trying to use this in the inspector, im making this for a custom graph view window which uses this SO to save
i know you're not using unity's actions
but whom is this for?
im making this for my own projects
based on this code snippet you've shared, you are at the beginning of a very long journey
why not code using C#?
why code using graphs?
there is no value there
you already know how to program
the code is in c#
I want to make a sprite bloom and flash in the game. I already know how to change the bloom settings, I just want the bloom to at all show up when the game runs.
I need to edit during runtime because the in-game camera doesn't use post processing.
I already learned here that the project renderer needs to be set to URP. I know I can change this with GraphicsSettings during runtime but that still won't work because according to others here I will have to go through all of the game's shaders and make sure they are URP compatible.
So I decided to go with the Post Processing package instead since that uses the default renderer.
Again I got the bloom to work in the editor with Post Processing package.
But that lead to #💥┃post-processing message
the graph will change how it's executed
if I wanted visual scripting I'd just use bolt
if you want fast reloading, use a fast reloading tool. here's an example of one:https://www.reddit.com/r/Unity3D/comments/10v66xi/we_just_released_a_free_tool_which_lets_you_skip/
not really, it's pretty much done other than this bug
pretty much done
the journey is longer than you think
I need to edit during runtime because the in-game camera doesn't use post processing.
is this a mod?
yes
unless ur saying the solution to this specific problem is unnecessarily complicated no not really
none of this will work, sorry. you will have to figure out bloom another way
Just because I'm curious, do you know why bloom wont work with the post processing package? That just uses the default render pipeline and I'm not getting any errors as far as not having the right dll files referenced.
i'm not sure. i have never run into this problem before
your best bet is to write an email to the developer and ask to add a postprocessing v2 component to the camera in unity
Alright, is my only other option to figure out how to add bloom statically in photoshop?
Someone else recommended to draw it since it's a 2d game
yes, you can create a bloomed version of the sprite and swap it out
alright thank you
@undone coral maybe this will help to elaborate https://streamable.com/kx6ak0
heres the class for action data
[Serializable]
public class ActionNodeTreeData : NodeTreeData
{
[SerializeReference] public NodeTreeData pass;
[SerializeReference] public Action action;
public override void Run()
{
if (action != null)
action.Execute();
if (pass != null)
pass.Run();
}
}
heres the other class thats working perfectly fine in the list i mentioned before
[Serializable]
public class ActionNodeGraphData : NodeGraphData
{
[SerializeReference] public Action action;
public string inputPortGUID;
public string outputPortGUID;
public override BehaviourNode CreateNode()
{
ActionBehaviourNode actionBehaviourNode = new ActionBehaviourNode()
{
GUID = GUID
};
actionBehaviourNode.Create();
actionBehaviourNode.SetPosition(new Rect(position, Vector3.zero));
actionBehaviourNode.actionObjectField.value = action;
actionBehaviourNode.inputPort.GUID = inputPortGUID;
actionBehaviourNode.outputPort.GUID = outputPortGUID;
return actionBehaviourNode;
}
}
i'm sorry i can't be more help. you can take a look at the existing behavior tree implementations for good approaches to doing this
you should probably use a custom serializer to serialize graphs
and not use the unity serializer
[SerializeReference] on an Action doesn't make sense to me
because you wrote that, it makes me feel like you don't know what's going on
thats what i was told to do when i came here before
here
i think if you want to achieve this, there are existing behavior tree implementations
unless you specifically aspire to create unity editor tools
you are on a journey that is low ROI
graphs are not that valuable.
especially if you are a solo developer, and you already know C#
part of this journey, why i keep saying you're at the beginning of it, is ditching code
ditching this stuff and fighting the inertia of having a lot of code written
let me show you an example of inertia: https://github.com/weaveworks/eksctl/issues/5256#issuecomment-1130313683
here i am reporting a design flaw in a tool i use. i fixed it and used my fork in 15 minutes. i reported it may 13. because of inertia, a bunch of guys had these big conversations about how they are trying to avoid admitting they made an intellectual mistake. it took them until august 17th to fix it, which is 3 months
so i am telling you now, with no uncertainty, that the design of what you are doing is flawed, and there is a lot of inertia around the fact you have already written a lot of code and feel like you are close to the finish line
i mean this in a positive way
it's just about the why.
there's no why to having the graph
there are existing behavior tree tools
unless you specifically aspire to create unity editor tools
here's another perspective: Unreal engine has blueprints, and people use blueprints not because they are good but because C++ is so bad
do you know how many people with $0 budgets ship games with unreal? basically no one
you need a $250k budget to ship an unreal prototype
programming a game in unreal is essentially vaporware
every single person who has to make a game inside of unreal eventually has to become an expert in its peculiar kind of C++ development that vastly exceeds the expertise needed to master Unity's C#, so it's as though a game development SDK doesn't exist at all
so you don't need blueprints
you already know how to program well
you already have the superpower
you don't need to serialize graphs. you can express the graph in code if it's that important
it's not that bad
you don't need a whole authoring tool
lol
okay i don't know if i've persuaded you
i'm done
Is there an easy way to differentiate between None and Missing GameObjects?
I've found this post https://forum.unity.com/threads/how-to-check-if-a-property-is-missing-or-not-set-none.642919/ that implies that ReferenceEquals(gobj, null) should be true when gobj is None and false when it's Missing, but that doesn't seem to be true - it's false in both cases.
Would it be enough for them to push a version where they just installed the Post Processing package? Then modders can add to the camera themselves?
hmm, i'm not sure
i would probably test it on your own project if you feel ike you have only one shot at this
in most cases i agree and usually prefer sticking to code, however im working on a complicated character controller that id like to be very flexible, allowing for multiple characters with different behaviors without requiring u to rewrite the code for each individual character. I considered many option including state machines (and this solution isn't necessarily instead of state machines as I could still have other state machines within the graph, however in the way that this is a solution to the problem it does replace it), but decided that a graph would be a good solution for this. (i didn't actually know behaviour graphs were a thing before getting into this, im not surprised that they are since it wasn't a very revolutionary idea but the idea was reverse engineered from my specific problem).
im not sure if that explanation is satisfactory and i can elaborate if u want but im not sure if it really matters anyway...
as for the idea of expressing the graph in code I have considered this but there are a few reasons i decided against it:
- it's a behaviout tree- it isn't just one linear execution of events, there are many branching paths of where the graph will go. trying to cram it all into a one dimensional list of instructions could work however it could get very messy.
- i do plan to release the controller for others to use in their projects, most of them not having as much experience with c#. most of them can't even figure out how to install the input system so a bowl of spaghetti code definitely wouldn't be as friendly as a graph
anyway thanks for coming to my ted talk
character controller that id like to be very flexible
you clearly have the wisdom to know that this is an oxymoron
lol
you know a lot more about what you want to do than i do. in my experience, behavior trees are very useful for designing enemies in platformers
that's kind of the tradition they fit inside of
a lot of innovation in those games is in the level and npc design
the character usually behaves within a very narrow set of traditions. pretty much every 2d platformer authored by an indie game developer either has no meaningful complexity of movement (amanita design games) or it's megaman
and megaman explored this design space, it's very tightly coupled, it's almost 30 years old or whatever. to nail the megaman character behavior you need to write very tightly coupled stuff that a behavior tree, state machine, etc. - abstractions cannot conquer this
there are basically no solo developers developing games like overwatch, tf2, mobas inside of unity. they rely on engines like the warcraft 3 map editor to implement "spells." a really big design space. there's so so much engineering to support that design space. the WC3 editor, the roblox editor, hammer editor, etc. essentially have an in-game LISP that is disguised as an editor tool, and people like this, and they use it to program. it's not a graph, but it could be a graph, but it doesn't matter - the thing that matters is that the engine provides working multiplayer and graphics
roblox is also programmed in lua, and 14 year olds learn lua and it's fine, because the value is tied up in having working networked replication and correctness of rules
overwatch has a multi million dollar budget. if they want to explore the full team fortress 2 "FPS with spells" design space, they could do it literally however they want
they use literally everything. they have behavior trees, i'm sure, because one of their designers asked for it, and they have 1 billion dollars, so they delivered it
it doesn't mean that it makes sense
kinematic character controller in unity has figured out the 3d platformer tradition
and it's free now
2.5d corgi engine - i haven't even used it. i don't know if it nails the megaman movement
you give someone who doesn't know how to program a 2d platformer character and ask them to create an innovative movement, and they'll author a grappling hook. listen, it's been done
мб ты не будешь спамить в чат на целый экран в канале для помощи своей философией?
@distant tree so on the one hand, it's a big goal. on the other hand, you don't really need flexible character controllers in practice. they are in fact in opposition to the real goals.
people don't want to explore the whole design space of 2d platformer character movement. that's just not the tradition. you give a player a character that doesn't move exactly like megaman does, they will just quit your game
flexible character controller makes it much harder to implement megaman movement
i've said this a lot of times in this chat because so many people want to do innovative 2d platformers
I love how this is so much a meme and true at the same time ._.
you gotta put on your ludology hat and think what innovative 2d platformer really means, that's part of the journey.
especialyl if you want to author tools, which you do
you want other people to use this
this has more to do with the actual logic, not with using a behaviour tree to do it
my experience with specifically this problem comes from a colleague of mine
i haven't personally tried to make a behavior tree coexist with a megaman character controller, where the behavior tree lets you implement extra stuff the character can do
i know that it is essentially not possible. you wind up leaking all the abstractions of the megaman character movement. as long as you want a working game that people actually want to play*
if you just want to explore concepts for movement, make a video.
@distant tree here is an example: https://arstechnica.com/gaming/2020/07/nintendo-gigaleak-reveals-classic-nintendo-prototypes-source-code/
you can watch that video and be like, "okay, hanging off of pipes this way is innovative"
but the implementation of that character is tightly coupled. there's no behavior tree there
someone who is going to do soemthing genuinely innovative also will learn how to program
im not sure this is relevant to ur specific point but I think it'll help to give a little more context...
the character controller im working on is a 3d sonic the hedgehog character controller (however I plan to use much of the code in more original projects as well). the code for the actual character controller has already been done, I've just been exploring better ways to do it than my original approach of just cramming it all into a single script.
but sonic isn't a very simple character. you've got the spin dash, drop dash, homing attack, boost, and a million other abilities (especially if u plan to have multiple characters, which would add on another few million abilities) that execute differently depending on the state of the character
so i drew the logic out like this and thought "woah, it's a tree. maybe this will work well as a graph". and so I did a little research on similar things other people had come up with but I couldn't find anything that looked like it had what I needed, so i decided to try doing it myself, and here we are
I've just been exploring better ways to do it than my original approach of just cramming it all into a single script.
but this is how these things are made. you are like proving my point
i see from your diagram that you already know all this stuff
but it's hard to abstract away the things that make this actually work
the sonic attacks are all very tightly coupled
you already know this! it's in your lived experience
actualyl you would gain al ot from looking at corgi engine 2.5d
which has to be all things to all people
ur saying I should cram everything into a single script?
and you would see that basically the developers author a specific script, in their framework, to implement a traditional 2d platformer movement
i'm saying that this is what this kind of character implementation look slike
if your goal is to make something correct and feeling good
i don't even have an opinion about big or small scripts, it misses the forest for the trees
i don't think i've had an opinion about that for a decade at least
it's not bad if it's one big script
sometimes that's just what it looks like
actually one of the reasons I didn't stick to the single script thing was that i got a lot of comments saying it would be better to use a state machine or something and split everything up
Why not implement that tree, except instead of as an editor tree or whatever, just implement it as a tree in the code?
another reason tho was that, say i have multiple characters with different abilities, id either need a new script with duplicate code for each character, or i cram it again into the same script and it get exponentially even more complicated
this idea was mentioned earlier
here
You seem to be talking about “one giant script” which is a code organization problem, yes technically ditching code completely will avoid the problem, but you could also just architect the code.
im not ditching the code tho
okay, one perspective is that
you know, not everyone is a john carmack
or whatever
they can't just mozart the code out of their head
they look at a big file and get scared
those people may still be really good at programming though
even though it doesn't really matter, people who use tools do care a lot about vibes
and it's funny because the quintessential actionable feedback is people's vibes
my opinion: those other commenters were giving their approach to dealing with the bad vibes of big script files
i don't know. i can't get inside their heads
but since this is like a specific engineering problem with a long history
maybe their advice was wrong
they didn't Know
organization wasn't the only reason, in fact my initial reaction was that it didn't really matter that much
the other problem is that when u want to include multiple characters it's more than just a script, u get functions that go unused for some characters and it gets really hard to work with. organizing the code like this (whether with a graph or with the same concept thru code) allows u to reuse functions between characters if u need to reuse them or only use them once if that's what u want
only reason it isn't just a list of functions u can assign in the inspector or something is because, like I said, it isn't just one dimensional logic
hmm... but with multiple characters they sort of behave the same
unless you mean expanding the design space to "overwatch, but in 3rd person sonic controls"
which... is hard.
that's part of the problem
much of their behaviour is the same
so u want to reuse the code instead of copying and pasting it for each character
but some of the code is different, so why have it in the same script that will be used for a character that doesn't use that code
so my solution was to have each function act independently, so it doesn't matter how many times it's used
the behaviour tree is just there to determine which functions to run. like I said, it could have just been a list if it were just one dimensional and didn't branch out
Okay I see this specific perspective… but then why not configure it with bools
I’m only very loosely following the conversation so was pointing out that making it an editor one wouldn’t have much advantage over just code; if you are going to implement it in code then I don’t see much issue, maybe someone that have done it this way will have more insight.
Once the graph is authored it will never be changed
this is what the comment i was responding to was arguing (there were a few other comments in between)
unless I don't understand ur point
Personally when I don’t have a clear picture of how things should be architected, an easy way is to just write it the simplest way that works without employing any design patterns. Once it gets far enough and repetitiveness shows, the correct design pattern becomes apparent and you can factor it then. This is very similar to the green and refactor phases of TDD.
this is exactly what im doing
as I've said the logics all done already, I just need a better way to organize it that won't get in the way of adding additional characters
at this point most of the reason is that the graphs pretty much done already i just need to fix the saving issue. just doing it thru code wouldn't be too bad altho there are a couple other reasons I mentioned earlier
anyway looks like the problem was that the scripts were monobehaviour which scriptable objects apparently cant serialize- or they can, since they were doing it in the list, but that seems to be unintentional
might be able to get around this by serializing them in a monobehaviour and passing that onto the graph which i should've done in the first place. the list thing kind of threw me off
How could I get the amount of change around a given axis between two rotations?
ECS: In a baker, I need to add the following Shared Components to all child entities of the GO being baked (it's not a prefab entity).
Baker says I can't do that: [Worker38] InvalidOperationException: Entity Entity(28:1) doesn't belong to the current authoring component.
public override void Bake(BubbleAuthoring authoring) {
//....
foreach (var child in GetChildren(true))
{
var e = GetEntity(child);
AddSharedComponent(e, new BubbleGroup {value = bubbleKey});
AddComponent<DisableRendering>(e);
}
What's the correct practice to do this?
I tried adding a LinkedEntityGroup Authoring, but that also didn't work.
Wow, first time I really do not like Bakers, normally the pattern was really good, but for this case? Like, how is that even supposed to work now. 😄
Ok, I did the following, feels SUPER hacky:
public class BubbleChildBaker : Baker<BubbleChildAuthoring>
{
public override void Bake(BubbleChildAuthoring authoring)
{
var parent = GetComponentInParent<BubbleAuthoring>();
var group = new BubbleGroup {value = BubbleAuthoring.GenerateKey(parent.gameObject.name)};
AddSharedComponent(group);
AddComponent<DisableRendering>();
}
}
But it works, and since it's on a prefab I don't have to keep adding these.
I could use some advice. I had written some helper functions that would serve as no allocation versions of common Linq methods. (Where, Average, OrderBy, Count, etc)
I was aware of GetEnumerator and lambda expressions causing allocations, so I avoided those. I was not aware that passing an instance method also caused an allocation.
Consider the example code:
var count = CountNoAlloc(IsValid);
public int CountNoAlloc(Predicate<SomeType> predicate)
{
// Do Work
}
public bool IsValid(SomeType type)
{
// return true / false;
}
Is there a way I can call a common looping method without causing an allocation?
Or is there a known solution to this problem that I can leverage?
You can cache IsValid as a predicate and pass that into count
Are you saying the act of storing IsValid in a predicate variable is what is causing the allocation? So by setting it to a Predicate var I'm incurring that operation only once?
Passing an instance method or lambda shouldn't cause any allocations, unless the method has some kind of closure involved
Correct
Instance methods allocated in the past, I'm not sure what version of C#/.NET fixed it to behave the same as a lambda
Actually, it's not so much instance methods as just methods as arguments vs lambdas. Instance methods involve closures to pass the instance itself
Closure will also allocate, this case is allocating on the heap to store the predicate
That helps me understand whats going on under the hood.
You could create overloads that took additional arguments to be used in the predicate, that way nothing is captured
There are lots of minimal alloc Linq libraries out there though
Yeah as long as it needs to capture a variable from outside the lambda's scope, the compiler creates a whole class (sometimes struct for late .NET versions) and instantiates it. That's pretty much where most of the garbage comes from
@austere jewel I assume they'll have the same problem though.
regarding the other linq libraries (I'm happy to check out a recommendation though!)
Not if you use them properly. Here's a random one I found on Google just now https://github.com/cathei/LinqGen, presumably by @jolly token
I focus more on minimizing allocations in bottleneck areas than trying to use a generic low-allocation solution across the board, personally
Keep in mind Unity's GC is (optionally) incremental, too, so some garbage creation isn't as much a problem as it used to be
Hey could someone help me with a Vector3Int?
Vector3Int SpawnHere = new Vector3Int((int)SetGridPosition.transform.position.x, (int)SetGridPosition.transform.position.y, 0)
I am trying to add that SpawnHere to this
I have been looking over it and I still can't figure it out
my two best guess would be
adding it to this line
or
What are you trying to do
somewhere in this
I am trying to change the set position of tilemap grid that generates an island
I don't understand, this is all too context-free
ok so
what the code does in short is procceduly generate an island on top of a grid
with
verts
I have gotten it to spawn the island fully
but when I try to find a way to move it to a new location
it doesn't move
I know it's not Falloffmap
What is confusing you so I can better address the question
(don't mean to sound rude)
I don't understand why you're coming in with a line of code and asking where to put it, like a jigsaw puzzle
yea I have been having issues with this code all day I thought placing it here then maybe someone else had a different perspective
If you're just trying to offset your noise map, you would just add the offset at the end right before spawning an object or placing a vertex or whatever you're doing
The code that you showed doesn't spawn anything
What I am trying to do is not offset the noise map but set the position of the grid to another area
Yea this is just the part that states the grids references
then after start calls a DrawTerrainMesh(grid);
DrawEdgeMesh(grid);
Can someone tldr slip friction for me? In terms of vehicle physics? I completely understand how raycast suspension works and I've implemented sideways friction without any issues
I assume I'll have to model an actual "engine" and transmission for slip friction to work properly right?
allocation of small heap objects isn't super material. if you wanted to make a big contribution to the unity ecosystem, burst-compilable LINQ would be 😙 chef's kiss
the industry trend right now is huge caches, so all the garbage allocation mumbo jumbo is about to get even less relevant
which, by the way, all those game engines that people relentless try to avoid garbage allocation in, they all benefit immensely from huge caches, they were not necessarily correctly optimized for real hardware in the first place
i'm not even going to speculate why because it requires a degree in CPUology that some random tutorial author on the internet is not going to have
hey guys i am struggling so hard setting up a database in unity does anyone have some suggestions? I tried mysql but the app for it was to much so i switched to firebase got around with the website easily but anytime i go to write code for auth functions it keeps saying my app is not found and ive re downloaded the sdk have the auth installed and my json for google
Hi 🙂 I am trying to find a way to edit the 2d animation package to fix a known bug, but every change I make reverts. I've been searching how to edit Unity packages, and the best thing I have seen says I have to remove the copy the package and edit the copy, but that would break everything else even if it did fix my issue 😄 anyone have a direction for me?
@latent sorrel have you tried mysql?
Does anyone have any experience working with receiving software clicks/keyboard presses sent from Pynput to Unity?
So in Unity, interfaces are not serialized by default, right? However, we can get a component that implements an interface using GetComponent or serialize it using custom attributes or, for example, Odin. It seems to me that in terms of modularity using interfaces beats every other approach, so where's the catch? There must be disadvantages to it, other than it's not serialized by default?
i just got it now took forever im going to make a video on it because firebase docs is so outdated i got lucky fixing it
The catch here is that a member of an interface can be any type that doesn't support serialization
Either way, you can use SerializedReference for this
Right, and I read that SerializedReference is not as efficient as by-value serialization, so that's a disadvantage here
In the new inputSystem there's unmanaged api for raw input access, you can start from there..
(I wanna talk but just tell me when there's room for me to ask my question, I can wait and I see there's a conversation going atm 🥺)
Okay there hasn't been any messages for like 10 minutes sooo
I was on here yesterday getting help about making my selection logic class more solid
So I've realized that I can break it down more and I've basically gone from this first class to the new one
public class TestSelectionManager : MonoBehaviour
{
// Whether an object is currently selected.
private bool _selectionActive;
// Transforms currently and previously under the mouse.
private Transform _currentSelectable;
private ISelectable _selection;
private ISelectable _previousSelection;
public delegate void Hover();
public event Hover ObjectHovered;
void Update()
{
if (_selectionActive)
{
if (Input.GetMouseButtonDown(0))
// Initiate deselection behavior.
{
_selection.OnDeselection();
_selectionActive = false;
}
}
else
{
// Gets the highest Transform under the mouse according to sorting order.
_currentSelectable = MyNamespace.Selector.UnderMouse();
if (_currentSelectable)
{
_selection = _currentSelectable.GetComponent<ISelectable>();
if (_previousSelection == null || _previousSelection != _selection)
// Initiate hovering pre-selection behavior.
{
_selection.OnHover();
ObjectHovered?.Invoke();
_previousSelection?.OnUnhover();
}
if (Input.GetMouseButtonDown(0))
// Initiate selection behavior.
{
_selectionActive = true;
_selection.OnSelection();
}
_previousSelection = _selection;
}
else
// "Forget" _previousSelection if the mouse hovers over nothing so
// the mouse can move away from and return to selectables.
{
_previousSelection?.OnUnhover();
_previousSelection = null;
}
}
}
}```
I took that and broke down ISelectable into ISelectable + IHoverable so the behaviors can be separate
and I tried breaking down TestSelectionManager into SelectionManager and HoverManager instead of having them both in one class
public class SelectionManager : MonoBehaviour
{
private ISelectable _selection;
public delegate void Selector();
public event Selector Selection;
public delegate void Deselector();
public event Deselector Deselection;
private void OnMouseDown()
{
if (_selection != null)
{
_selection.Deselect();
Deselection?.Invoke();
}
_selection = MyNamespace.Selector.UnderMouse<ISelectable>();
if (_selection != null)
{
_selection.Select();
Selection?.Invoke();
}
}
}
I just want to know
Am I doing this correctly? Is this okay? I want to get into good/proper practices as fast as I can, so I want to know if I'm doing too much or still doing too little
Anyone has any idea how ScriptableObjects work with Domain Reload and without it?
Do they get fully new instances of C# objects or are they reused?
I am particulary interested in InputActionsAsset, since I subscribe to it and I have my domain reload turned off.
I mean, you should dirtying the SOs anyway or else it won't get saved
could you elaborate what does it mean?
you're using the SOs to save some state while in edit-mode or nah?
no
I use InputActionAsset because it has events for input
in runtime
and I wonder whether C# objects are reused
for SO
since without DomainReload I can potentially get same instance with dead event references
hop on to #↕️┃editor-extensions we can talk there
🤔
Hi. Got an advanced code question for the group. I am making a Command system for a turn-based game, which includes nested commands. Here's an example of one of my hierarchies:
{
void Execute();
}
// This generates a path and calls...
class Command_MoveAlongSpline
{
int NumberOfMovesMaximum;
Command_SingleMove SingleMoveSubCommand;
void Execute();
}
//... Which iteratively calls...
class Command_SingleMove
{
bool PreserveFacing;
void Execute();
}```
Problem is that right now if I create a new Command_MoveAlongSpline, I have to also give it a variable for PreserveFacing if I want the Command_SingleMove to reflect that setting.
I'm wondering if I can properly embed the subcommands into greater commands so I can do something like "var NewCom = new Command_MoveAlongSpline(); NewCom.SubCommand.PreserveFacing = true").
Ideally with the sub commands accessible through Inspector.
In addition, I would like to be able to clone the subcommand so I can configure it without it being changed for every other command instance.
You can do that, but in my opinion it kinda defeats the whole point of designing any system in the first place.
Maybe pass in a CommandContext or something that has different subtypes with different parameters. Then each specific command can try casting it to the appropriate context to retrieve the parameters that it needs.🤔
Just make them Serializable and their fields serialized.
Will need to implement a clone method that copies the command fields into the other instance.
Ah, that works. Now I need to figure out how to clone them.
The intent being that I can embed a Command_MoveToHero in another script, and copy it on each turn when running instead of re-using the same one every turn.
hi guys, can you use the native C# parallel for each loop in unity? i tried it but i get this error Assertion failed on expression: 'gCurrentManagedTempMem != NULL'
Should work but obviously it might run in different threads so most of Unity's api is off limits
hmm ok, so only certain things will allow it
hi, sorry another question, i know you cant use reference types in a job struct.. but is there an 'easy' way to work around that?
InvalidOperationException: GetEnemyActionJob.action is not a value type. Job structs may not contain any reference types.
public struct GetEnemyActionJob: IJob
{
public GridPosition gridPosition;
public BaseAction action;
public void Execute()
{
action.GetEnemyAIAction(gridPosition);
}
}
Have you tried #1062393052863414313 ?
i haven't i will try ty
@undone coral worked good 🙂
Each layer has a "Blank" animation which can be replaced once the meshes have been assigned. The Avatar masks nicely allow me to filter out the bones which should move in each layer
you dont need a avatar assigned to the animator when using avatar masks
Does anyone know why this might be throwing a cast exception?
Convert.ChangeType(registryInstance, iRegisterClosed)
So the registryInstance is a type that inherits the IRegister interface. They both are generic, and when I log the variables they match what they should be.
Levels.Universal.Experimental.IRegistery`1[UnityEngine.GameObject]
Levels.Universal.Experimental.RegisteryService`1[UnityEngine.GameObject]
But I am getting the error.
InvalidCastException: Object must implement IConvertible.
The classes for reference
public interface IRegistery<T> {
RegisterKey Key { get; }
Func<IScope, string, T> Fufiller { get; }
}
public struct RegisteryService<T> : IRegistery<T> {
private readonly RegisterKey _key;
public RegisterKey Key { get => _key; }
private readonly Func<IScope, string, T> _fufiller;
public Func<IScope, string, T> Fufiller { get => _fufiller; }
public RegisteryService(RegisterKey key, T instance) : this() {
_key = key;
_fufiller = new Func<IScope, string, T>((s, t) => { return instance; });
}
}
And the rest of the code leading up to the error.
foreach (var service in Services) {
Type ServiceType = service.Obj.GetType();
Type exportOpenType = typeof(Exports<>);
Type exportClosedType = exportOpenType.MakeGenericType(ServiceType);
Type iRegisterOpen = typeof(IRegistery<>);
Type iRegisterClosed = iRegisterOpen.MakeGenericType(ServiceType);
Type registryOpen = typeof(RegisteryService<>);
Type registeryClosed = registryOpen.MakeGenericType(ServiceType);
ConstructorInfo registryConstructor = registeryClosed.GetConstructor(new Type[] { typeof(RegisterKey), ServiceType });
object registryInstance;
if (service.Obj is not GameObject) {
registryInstance = registryConstructor.Invoke(new object[] { new RegisterKey(service.Tag, ((Component)service.Obj).gameObject), service.Obj });
} else {
registryInstance = registryConstructor.Invoke(new object[] { new RegisterKey(service.Tag, ((GameObject)service.Obj)), service.Obj });
}
MethodInfo registerMethod = exportClosedType.GetMethod("Register");
registerMethod.Invoke(null, new object[] { _source, Convert.ChangeType(registryInstance, iRegisterClosed) });
}
Ah my types would need to implement the IConvertible to work,,, would Castle.Core have an alternative way to cast to the interface without that, and without knowing the concrete(or what ever you would call this) type?
Or anyone know how to implement IConvertible for the above as the Microsoft document example calls the Convert.ChangeType method which seems like would cause a circle in calls.
Do you need to sync it? Does it have any logical effect?
You might need to send what your IK target/ targets position is. But if the IK is purely visual it should be able to calculate most from the state of the game?
Game state, e.g. positions, jumping, shooting, ammo etc.
Lets say you have an IK for your right hand to grab a mug of beer, that you can later drink to gain some stamina. Your game state will tell that you're grabbing the drink state, this is replicated. The state triggers an animation and sets your IK target to the beer mug locally.
I'm running code in a tick based controller, like so:
public class TickBehavior : MonoBehaviour
{
public int currentTick;
private CustomTime _time = new CustomTime();
private float _tickTimer;
private const float SERVER_TICK_RATE = 30f;
public const float MIN_TIME_BETWEEN_TICKS = 1f / SERVER_TICK_RATE;
public float tickDelta;
public void Update()
{
_time.UpdateTimer();
_tickTimer += _time.DeltaTime();
while (_tickTimer >= MIN_TIME_BETWEEN_TICKS)
{
_tickTimer -= MIN_TIME_BETWEEN_TICKS;
HandleTick(currentTick++);
}
}
public virtual void HandleTick(int currentTick)
{
}
}```
Because my player movement happens in HandleTick, the camera is very choppy.
I was hoping someone might have a few suggestions on what can be done.
Is your camera a child of your player ?
And, is there a reason why you want a tick base controller ? I just hope you are not doing it to synchronise your Server and Client.
Thanks for the recommendation! I'll check it out and hopefully that handles the software clicks/presses I am currently working with
hope you get the idea here, I was putting it in italic so you'd aware what unmanaged territory means.. it's not a common api to be used in Unity in general and they're hiding it for a good reason
no, but it is pretty straightforward to create devices and input events for input system
you don't have to use unsafe to do this
🌈 that's all
what is the application?
what is your goal? there is a lot going on here
there are SDKs with this kind of stuff in mind. for example you might want to use Normal instead of photon. all of them have flaws.
I have a Python based Assistive Deivice receiving UDP packets and outputting Keyboard presses using Pynput. I was able to find a solution using Input System's Keyboard class
okay, here's an example for keyboard:
this is sufficient for a working keyboard
and covers all the nuances
you will have to author your own Parse method obviously
does this make sense to you?
you shouldn't be using udp broadcast.
it will not work on most networks
but i think you are receiving from python, so it's all local
I appreciate the advice but I was only looking for a keyboard input method, I don't need this to pickup the UDP packets
the udp packets from the device?
how does your python process communicate with unity?
it's
some hardware <--> python --> unity
right? is your idea?
The idea is just via keyboard presses via Pynput, and I was already to figure that out using the new Input System I was recommended above
Yes.
so how does python communicate with unity?
the snippet i shared shows how to do keyboard-like events, but it's kind of nuanced so it's worth taking a careful look
I was already to figure that out
it might be a little premature to say that
there's also input remoting, which is harder to use but even more robust.
👍 thank you
let's say you had a script
class TooltipController {
public Tooltippable lookingAt;
private bool hovering;
...
void Update() {
if (hovering) {
Show(lookingAt.description);
}
}
}
then you can do
class Tooltippable : MonoBehaviour {
[SerializedField] private string defaultDescription;
public virtual string description => defaultDescription;
}
class UnitTooltippable : Tooltippable {
public Unit unit;
override string description => $"{unit.name}: {unit.hp}/{unit.baseHp}"
}
class ResourceTooltippable : Tooltippable {
public Resource resource;
override string description => $"{resource.name} ({resource.quantity})"
}
void OnHover(GameObject target) {
tooltipController.tooltippable = target.GetComponent<Tooltippable>();
}
do you see how this makes interfaces redundant, and Just Works in the default inspector? and it doesn't use [SerializedReference] which is radioactive? and you can really easily customize what you want to do, intuitively? by dragging and dropping components onto prefabs, which is the easiest thing in the world?
but how does python communicate with unity?
poorly?
with threads and like a bajillion lines of code?
@whole juniper the unity python package only works in editor
it doesn't work in a built player
so it's worth talking about this, before you find out you have a lot more work left to do
it sounds like you're using the unity python package
which won't work
I'm not using the Unity python package. Python scripts are being run separately as part of a different application.
so you're writing a text file, and unity is reading it repeatedly?
it sounds like your python program is writing to a text file the state of the keyboard, and the unity is repeatedly reading this text file
or maybe you are trying to start an http server inside of unity, and the python program is calling a URL on it?
anyway it sounds like you haven't gotten there yet
do you see any benefit to using interfaces in unity?
Is possible to enable burst on specific methods? Putting BurstCompile in a method doesn't show it in the Burst Inspector?
That only seems to show jobs...
Also, another partially related question. Is is possible to make methods with BurstCompileAttribute to call managed methods?
no
Burst compiler only means anything in jobs, and jobs cannot call managed code
But can I put BurstCompile in methods which aren't from jobs?
I read it's possible, but I don't find those methods in the Burst Inspector.
less than in the bigger .net ecosystem. interfaces exist to work with closed libraries, sdks, and for things that look like dependency injection. if you have access to all your source, like you usually do in unity, they aren't as useful and add baggage
Method must be static and both the method and the containing class must have the BurstCompile attribute
Ahhhhh, I wasn't adding the attribute to the class
I thought that adding to the class was the same as adding the attribute to each method
It's set up that way so Burst doesn't have to check every method, increasing your compile time.
Make sense
hmm. i get that, but I always seem to run into issues relying too much on inheritance. e.g. - both items and characters needing to be IInteractable - but only items needing a base Item class, and characters needing a base Character class. you could have both bases also inherit of a base Interactable - but what do you do when a character shouldn't be interacted with?
that's why it's a base class of interactable, and a CharacterInteractable and ItemInteractable script that "adapts" a Character and Item into something Interactable
that approach has existed for decades, it's basically the delegate field in all the apple objective-c frameworks
the annoying thing about interfaces in your example is that you wind up using the methods as a form of type system
which is very clunky
you would want all that clunk to live in ItemInteractable
you wind up needing to put code somewhere that isn't in the method IInteractable declares; or, you have to if (interactable is Character character) to extract the character field somewhere
with CharacterInteractable : Interactable { public Character character; ... }, you have all the stuff you need in the script and it stays out of the way
and GetComponent<Interactable> Just Works
but what do you do when a character shouldn't be interacted with?
so in my model, you don't attach aCharacterInteractableto that character's prefab
👀
the prefabs are already "a collection of traits". components are already the business part of interfaces
however, if i was a plugin author, i'd do BaseInteractable : IInteractable, and everywhere in my API, i would expect an IInteractable
because sometimes people want more power
hey there fishyfred! :>
I thought about pinging you with my progress but didn't know if you were good with pings or not
I tried separating my class into 2 classes (and the interface into 2 interfaces) to manage hovering and selecting separately
but now I've run into a problem - I can't pause hovering whilst selection is active, but I'd like to do that
the way that I see a remedy whilst keeping the classes separate is making an intermediary class that enables/disables the hover manager class as necessary
but is that bad practice?
disclaimer: im not the best to ask for this
it's hard for me to say without seeing what you mean, but my gut feeling is that you're not seeing when it's appropriate to separate things out into another class. if you need an intermediary class to allow 2 classes to do a relatively straightforward job, you're introducing a lot of coupling for not a lot of benefit
so yes, bad practice to introduce more classes for that example, since your hover and/or select classes should be able to expose what they need to to work correctly
It is to sync my server and client, with client side authority. I'm frustrated because it's been a long journey to achieve it, and this is the best I have managed so far.
Is there any reason why you cannot use a buffer ?
Anyway, you did not answer the original question which is: Is your camera a child of your player ?
As your character is moving in your handletick at fixed intervals at 30fps, you might have updates called at a higher rate, so the character will be choppy, and in turn the camera.
You can use the Updates in between your 'HandleTicks' to interpolate the characters position
In my experience, the camera is sluggish because there is a disconnect between the movement of the player and the camera which result in a non-constant movement between the rendering of the frame. I've experience such issue with using FixedUpdate for the movement of my character. My solution was to take the camera out of the hierarchy of the player and use a Lerp to smooth the movement.
Have you try using LateUpdate()?
Likewise the body should never have a new position between the end of LateUpdate and the start of Update(atleast rendered).
Hi everyone, is there a way to change the formatting of logs in the logging file Player.log?
I would also be interested if it's possible to omit this timestamp from the editor logs
never mind, I think I'll just use #if UNITY_EDITOR and change the formatting that way
In my case, my player had to be in the FixedUpdate because it was driven by the physics. Using LateUpdate or Update was potentially causing issue such as inconsistent amount of force applied to the body. This issue can be seen whenever the frame rates are asymmetric.
By example:
If you want to add a force in function of the distance of an object that is physic base.
If you use the Update function you may have 2 Update calls for 1 FixedUpdate calls
Those 2 Update calls will use the same position
Resulting in the same amount of force applied
Instead, the second Update should have used the modified position that result from the first Update
Which could have and probably would have result in a different amount of force
But like I said, the solution was to move the Camera outside of the player and move the camera independently from the player in a smooth manner.
Mesh slicing triangle intersections
I have one externall dll that is not compatible with skip reload domain, anybody has figured out way to force reload of single assembly or is it always all or nothing?
Hi guys! What is the best way today of culling UI elements. I want to disable UI element gameobject when it outside of scroll view.
you should use the asset optimized scroll view adapter
i would post a copy of the assembly directly onto the unity forums about the feature, and maybe a unity engineer will notice
I cannot do that, as said, its external dll which is not to be distributed
If you use the Update function
you shouldn't add forces in update right?
author will fix it eventually but was looking easy fix meanwhile
I'm trying to demonstrate why you should use the FixedUpdate instead of the Update by explaining what could happen if you use the Update for physic calculation.
So, yeah. Do not use physics in Update.
What is this? Where can I read about it?
can i use c# 11 in unity?
Does anyone have any suggestions on how I gracefully strip a monobehaviour's values in a build but keep it in-tact in the editor? If I strip out values using UNITY_EDITOR then I get in an error in runtime saying
A scripted object (probably xxxxxxxx) has a different serialized layout when loaded. Read (32 bytes) expected (208 bytes). Did you you #ifdef UNITY_EDITOR a section of your serialized properties in any of your scripts?
The reason why I want to strip out values in a build, is that I don't want to bring in debug-only data into the build
I could have two separate scenes, one for builds and one for use in-editor, but that's a headache
Can you put your Debug data on a separate/child GameObject?
https://forum.unity.com/threads/editor-only-monobehaviour.508844/#post-3322419
Thank you, it looks like using the EditorOnly tag on the object is the way
return a List, Array, or IEnumerator, or any other collection
I mean your return type is already an array
so return an array
loops are not objects
they are control structures
however
C# does have iterator methods
where you can do:
for (blah blah ) {
yield return xyz;
}```
99% sure you just want return item; in your case though
you are at the start of a long journey, #💻┃code-beginner
I'm in a bit of a tangle here with some async stuff. I haven't had to do much of this so I'm a little rusty.
I'd like to create a task or async operation that allows me to load up a bundle of scenes (one main one and a bundle of additive ones), and check progress on them via this "parental" task/operation. How might I go about doing this?