#archived-code-advanced
1 messages · Page 90 of 1
Why would you need to download it? It should be included in a build automatically if you're using it and the platform supports it.🤔
Reflection not found from Beeee
What platform are you building for?
And is it Il2CPP build?
while processing scripts
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class script : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
object result = CSharpScript.Evaluate("1 + 2");
Debug.Log("result = " + result);
}
// Update is called once per frame
void Update()
{
}
}
unity seems to have died
relaunches unity
ignores compilation errors
Unity seems to have its own version of the code analysis package that the CSharpScript class belongs to.
Refer to this forum post:
https://forum.unity.com/threads/dots-visual-scripting-first-experimental-drop.677476/page-2#post-4598263
<b><color=#bb4444>[CscSettings]</color></b> This is first compilation. Request script compilation again.
UnityEngine.Debug:Log (object)
Coffee.CSharpCompilerSettings.Logger:LogInfo (string,object[])
Coffee.CSharpCompilerSettings.CustomCompiler_2021:Register ()
Coffee.CSharpCompilerSettings.Core:Initialize ()
UnityEditor.EditorAssemblies:ProcessInitializeOnLoadMethodAttributes ()
System.Exception: Reflection not found: Driver in Bee.BeeDriver.ActiveBuild
at Coffee.CSharpCompilerSettings.ReflectionExtensions.Get (System.Object self, System.String memberName, System.Reflection.MemberInfo mi) [0x00077] in <1953dcd1da5444c992e14e6e66b4207b>:0
at Coffee.CSharpCompilerSettings.CustomCompiler_2021.OnCompilationStarted (System.Object state) [0x00006] in <1953dcd1da5444c992e14e6e66b4207b>:0
at (wrapper delegate-invoke) System.Action`1[System.Object].invoke_void_T(object)
at UnityEditor.Compilation.CompilationPipeline+<>c.<SubscribeToEvents>b__26_0 (System.Object context) [0x0000b] in <4ec4ffcbf9cb40b9a62b20bd9f80de36>:0
UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:TickCompilationPipeline (UnityEditor.Scripting.ScriptCompilation.EditorScriptCompilationOptions,UnityEditor.BuildTargetGroup,UnityEditor.BuildTarget,int,string[],bool)
System.NullReferenceException: Object reference not set to an instance of an object
at Coffee.CSharpCompilerSettings.CustomCompiler_2021.OnCompilationFinished (System.Object state) [0x00038] in <1953dcd1da5444c992e14e6e66b4207b>:0
at (wrapper delegate-invoke) System.Action`1[System.Object].invoke_void_T(object)
at UnityEditor.Compilation.CompilationPipeline+<>c.<SubscribeToEvents>b__26_1 (System.Object context) [0x0000b] in <4ec4ffcbf9cb40b9a62b20bd9f80de36>:0
UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:TickCompilationPipeline (UnityEditor.Scripting.ScriptCompilation.EditorScriptCompilationOptions,UnityEditor.BuildTargetGroup,UnityEditor.BuildTarget,int,string[],bool)
Assets\script.cs(10,25): error CS0103: The name 'CSharpScript' does not exist in the current context
but the C# compiler is not included in the Unity Player builds, right? (eg, cannot be accessed at runtime outside editor)
Yeah, you can't use that at runtime probably.
which is why i need to try to include my own
I don't think that's gonna work. It's a system library. It probably has some dependencies on the platform and os.
Actually. Maybe the unity package would work in a build too.🤔
i cant seem to find anything online about System.Exception: Reflection not found: Driver in Bee.BeeDriver.ActiveBuild
might be a conflict from https://github.com/mob-sakai/CSharpCompilerSettingsForUnity
imma try using openupm-cli if it doesnt work
now i just get
Assets\script.cs(10,25): error CS0103: The name 'CSharpScript' does not exist in the current context
oh
Code Samples
Note: the samples require the following using:
using Microsoft.CodeAnalysis.CSharp.Scripting;
oof
Assets\script.cs(10,25): error CS0234: The type or namespace name 'Scripting' does not exist in the namespace 'Microsoft.CodeAnalysis.CSharp' (are you missing an assembly reference?)
installs via openupm
A new scoped registry is now available in the Package Manager. o.o
hmm Assets\script.cs(4,37): error CS0234: The type or namespace name 'Scripting' does not exist in the namespace 'Microsoft.CodeAnalysis.CSharp' (are you missing an assembly reference?)
"org.nuget.microsoft.codeanalysis.csharp": "4.8.0"
},
"scopedRegistries": [
{
"name": "package.openupm.com",
"url": "https://package.openupm.com",
"scopes": [
"org.nuget.microsoft.codeanalysis.analyzers",
"org.nuget.microsoft.codeanalysis.common",
"org.nuget.microsoft.codeanalysis.csharp",
"org.nuget.system.buffers",
"org.nuget.system.collections.immutable",
"org.nuget.system.memory",
"org.nuget.system.numerics.vectors",
"org.nuget.system.reflection.metadata",
"org.nuget.system.runtime.compilerservices.unsafe",
"org.nuget.system.text.encoding.codepages",
"org.nuget.system.threading.tasks.extensions"
]
}
]
}```
imma try re-opening
hmm
> openupm view org.nuget.microsoft.codeanalysis.csharp.scripting
(node:59884) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
ERR! 404 package not found: org.nuget.microsoft.codeanalysis.csharp.scripting
can anyone create a sample project with Microsoft.CodeAnalysis.CSharp.Scripting package installed and working at runtime
as i still get
Assets\script.cs(4,37): error CS0234: The type or namespace name 'Scripting' does not exist in the namespace 'Microsoft.CodeAnalysis.CSharp' (are you missing an assembly reference?)
Hey all, I ran into a very weird problem with Threading on Android.
Here is my code:
void Start()
{
Thread thread = new Thread(inferThread);
thread.Start();
}
void inferThread()
{
Dot.SetActive(true);
results = objectDetector.infer(bgrMatCopy);
Dot.SetActive(false);
} ```
On desktop this crashes (as it should) because you can't access the "Dot" GameObject from a thread. But in an Android build this works fine. Which makes me suspect it's not actually creating a thread.
Any ideas what's going on?
that's just recoil, no? the crosshair just follows where the gun is actually aiming along with the recoil
hey can someone help me with my terrain system to implement octree for better performance and higher detail
or were you perhaps referring to the weapon turning slightly before the body? either way though, this isn't really a code question
yes, that's just moving the crosshair instead of locking it to the center of the screen. create a ray from the front of the gun, choose a distance along that ray and convert the position to screenspace and you have the crosshair's position
I am working on an custom animation curve thing. I am working on making controls for it. But having a hard time figuring out how to draw the in/out tangents so that they are a constant radius of the keyframe. The tangent is just a float.
It is one of those things where I feel like I almost understand what I need to do, but just not clicking.
What does "a constant radius of the keyframe" mean?
Do you want to use the ranges attribute of CurveField to restrict it to a rect?
Sorry I worded that really badly. I am wanting to make my own control for my own AnimationCurve. So when drawing the tangents for a keyframe, I want to mimic Unity's implementation where the tangent is shown as a handle rotating around the keyframe knot.
I'm unsure what the difficulty would be; in UITK you could position a rect on a point and translate it by half its length, or position it manually, or draw it using painter2D
The difficulty is that the tangent is a float. Not a Vector2
I am just about to implement something similar myself so I can look into the logic behind it too
Oh, cool! Let me know what figure out if you could. Will do the same if I figure it out as well 🙂
The docs seem to say it's just a rise/run, but that doesn't completely make sense to me so I'll have to check
It just looks like the rise / run, where run is 1
I'm not familiar with that?
It's the gradient of the slope of the curve
0 if flat, and it cannot be vertical (undefined)
so to draw the tangent I'd find the aspect ratio of the view, width / height and use that as x, and math.atan2(tangent, aspect) should be that angle in radians
(untested)
atan2 seems like the right track...? I guess I am not quite following what you mean though
The value of the tangent is the y side of a right-angled triangle where the other side is 1.
The view into the curve isn't necessarily a square though, where the X and Y axes are the same length. So to find the correct angle for the tangent you need to involve the aspect of the view. So, multiply the 1 by the aspect, and feed those x and y values into atan to get the angle of the hypotenuse line formed by the X axis and the tangent value (the length of the y-side)
Hmm, I re-read this so many times and trying playing around with it. But my lack of any sort of math knowledge beyond the most basics is really holding me back here I think.
With that said, I poked around Unity's code and I think I kind a got it???
Which is basically just
Vector2 dir = new(1, keyframe.TangentOut).normalized;
float dx = nextKeyframe.Time = keyframe.Time;
Vector2 resultDir = dir * dx;
Here is were I was reading from https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Animation/AnimationWindow/CurveEditor.cs#L3146
That also works, what you do depends how you're drawing the line
They use a NormalizeInViewSpace function to do the aspect stuff
Looked like it had to do with zooming in and out I thought https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/Animation/ZoomableArea.cs#L599
You know what though, I'll take it. Few things to iron out, but even still. If it works that is good enough for me. Thank you very much Vertx! 😄
I think I'm losing my mind here, why is this variable being set to "" before Awake:
#nullable enable
namespace EffortStar {
public class NarrativeController : MonoBehaviour {
// ...
string? _leftCharacterId;
string? _rightCharacterId;
// ...
void Awake() {
if (_leftCharacterId == "") {
Debug.LogError($"{nameof(_leftCharacterId)} is empty string", this);
}
}
}
}
I must be doing something wrong somewhere
is your inspector set to debug mode? if so, then private variables are being serialized so unity is assigning an empty string to it
yes it is
Damn, that is wildly shit
I didn't realize it actually changed their values
I thought it would just render them to the screen using reflection
why would it do that???
yeah, you should be able to mark as [NonSerialized] to get around that. no idea why it does it though, i assumed the same as you but i guess it's probably easier to just serialize everything
Thanks for the info. I'm going to try it out now
Just had to go AFK for a second to decompress after an hour of confusion
Damn, wasn't it. I must be makign some other mistake
ah, no. it was it!
thanks
I had it in two places
Hi
I have a script that calculate an azimutAngle and polarAngle from joystick input. Then creating a quaternion rotation from those two angles and using Lerp to rotate the target. With this i am able to move a object with the joystick so that it points forward with 0,0 and is rotated to its side if i press full left.
The issue i am getting is that when i move the object from left to right it rotates around itself it. And is "upside down". Noticed that if i switch the polar angle to positive or negative the behaviour is the other way around. Have been using ChatGPT and Muse.
// Calculate azimuthal and polar angles based on joystick input
float azimuthalAngle = Mathf.Atan2(horizontalInput, -verticalInput) * Mathf.Rad2Deg;
float polarAngle =
Mathf.Asin(Mathf.Clamp01(Mathf.Sqrt(horizontalInput * horizontalInput +
verticalInput * verticalInput))) * Mathf.Rad2Deg;
// Scale the polar angle based on the sphere size
polarAngle = _sphereSize;
// Create a quaternion based on azimuthal and polar angles
Quaternion rotation = Quaternion.Euler(-polarAngle, azimuthalAngle, 0f);
// Apply the rotation to the child object, taking into account parent's rotation
targetObject.rotation = Quaternion.Slerp(targetObject.rotation, parentObject.rotation rotation,
Time.deltaTime * rotationSpeed);
Hi,
I want to debug log the stacktrace like the ones that is outputted when there is a runtime error that logs all the previous method calls.
how to?
Debug.Log does this already
no?
As does Debug.LogError
I'm inside a static class and method
Yes it does
That's not relevant, debug.log always prints the stack trace
It is itself a static method
oh, yeah. I miss one part.... I need more than the script call, i want the scene gameobject that execute the previous script call
You would have to include that information manually. That information won't be available by any automatic means
Put Debug.Log(name) on line 27 of TextView.cs and see what it prints just before the warning
or use the debugger
is there any way to tell if the player is running on an embedded gpu?
you could try Process.GetProcessesByName(processName) then inspect the returned Process array and see if you can get it from there.
We did similar to what you're trying to do but kinda forget what we used back then
I don't think Unity has an api for this, I might be wrong, you should double check
I'm wondering now if it would be better to just use a blacklist of unsupported egpus (eg intel HD/UHD) since there are going to be a bunch of high end ones that should be good enough
I honestly think you shouldn't be too concerned about that
there isn't that I can see, can't tell if you get dedicated vram either 😦
if their hardware aren't powerful enough to play your game due to ancient gpus, it's on them
we've already had someone complain about the game being "glitchy" when they have a dainty laptop, so just going to put a warning at start up
some people just don't understand
Is it possible to search for object in scene that has a class that contain a property of a specific type?
runtime? if so, better to pool them in a static List/Dictionary after instantiation (Awake or Enable)
no, I need it editortime
hey guys, how can I make the tests runner to finish testing all elements in a list even if it fails for 1 element
yes, reflection
can you give me an example?
#if UNITY_EDITOR
[MenuItem("Tools/Localization/Find empty text")]
private static void FindReferences()
{
// GameObject.find
search for classes that contains string property empty
}
#endif
no but look at
https://docs.unity3d.com/ScriptReference/Object.FindObjectsOfType.html
https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo?view=net-8.0
Is there any caveats to using source generators in Unity? Cause this feels like it is going to speed up editor tooling a ton.
Two major points:
- Unity does not support project reference, so you have to build the SG project separately and copy the dll over. You can automate this to make it easier for you, but it's not that big of an issue because SGs tend to be "write once and done."
- Unity doesn't not support the latest incremental SG, so you are stuck with the old one with worse performance. It shouldn't be too much of an issue, I have a nearly 100k LoC project with heavy use of SG and I don't see noticeable performance degradation.
SG and editor scripts can both fulfill the role of code generation, and my general advice is that if you want to generate code purely based on code and generate immediately (so you don't need to tab out of IDE back to Unity editor, wait for it to run, tab back into your IDE), SG is a good fit; otherwise consider good old editor scripts.
Sweet, so nothing really.
I wanna write SGs for parsing UXML to do stuff like automatically querying elements so I don't have to write a bunch of rootVisualElement.Q<Button>(className: "some-class-name");
And hooking up ListViews and Buttons and that sort of thing.
And then probably another one for creating 'viewmodels' classes that automatically get certain properties in a SerializedProperty/Object
Yeah those sound like really good use cases of SG.
MVVM Toolkit has the exact same idea: https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/overview
Yeah, I'm familiar with the MVVM communitytoolkit. I have actually been doing stuff with Avalonia.ui (like WPF) in my free time which is part of what gave me the idea to try out source generatos.
I'm not sure if it is better to just do automagically and match method names with button names/classes. Or do explicitly use attribute, or an attribute with a uxml class/element name... gotta think about it I guess.
But this will take down the boilerplate I write by sooo much
Maybe partial methods for somethings like ListView make/bindItem... 🤔
Not really sure what sort of 'best practices' there are for SGs
Yeah I think the general consensus is to make things explicit so it's clear what's being generated, and helps with debugging too, rather than relying on some opaque rules like naming a certain way.
But, in some cases I do think generating implicitly based on rules is fine, eg stuffs like DTO for JSON where they serve one purpose and one purpose only.
DTO?
Eg:
[Json]
public partial record GameSave(int Level, float Hp) {}
var gameSave = JsonUtility.From<GameSave>(someJson);
gameSave.Validate();
In this case stuffs are generated (eg validation) implicitly based on the fields Level/Hp with no explicit annotation, but is imo fine because GameSave serves that one single purpose.
Ahh that makes sense.
Just trying to understand common usage. So if I wanted to bind a method to a button. Which would be the way you would suggest? B?
// Auto-generated
public Button LogMessageButton { get {..} }
// User defined.
// A: Auto matched based on the method name.
private void LogMessage(){ }
// B: Found by the attribute, auto-matched on the method name
[Command]
private void LogMessage(){ }
// C: Found and matched by the attribute. Method name dosn't matter
[Command(nameof(LogMessageButton))]
private void LogMessage(){ }
I'd probably go with B.
The issue with A is that you could be writing a LogMessage method that wasn't meant to be a command but rather just a private utility method, and one day you added a button that just happens to have the same name and suddenly they are wired together unknowingly.
C is a bit verbose but is fine if you prefer that explicitness.
Yeah that is kind of what I was thinking the issue was with A as well as I was writing that out.
If you don't mind. What about a ListView do you think, with its makeItem and bindItem? Same thing or would you do something different? I was considering maybe partial methods to force implementation?
Hmm that I'm not too familiar to give a suggestion.
SG does veer into the territory of API design though, it's almost like making your own library/framework, so you might need to go through a few iterations to settle on the one you like/fits your use case the most.
Just two events that the ListView requires you to subscribe to in order to have it draw the items.
But doesn't really matter too much. Thank you for the help! SGs are so cool, and going to save me so much time and make the code look so nice! 😄
Except for the SG code it self, that is ugly haha
Probably a single method to configure it would be nicer in this case? Not really sure if I'd like to have makeItem and bindItem be set up through attributes since it's probably the same amount of lines of code to write anyway. Could also get messy if you have multiple list views in the same script
The ListView recycles items, so they are actually different. But you might be right that just doing it 'manually' might be easier to read. Guess I will play around with format and stuff to see what feels nice
Just to clarify, by single method I meant something along the lines of void Setup(out Func<> Make, out Func<> Bind). But no clue what's a nice way to do it
Ahh, like that. Probably easier to still just use two methods or manually assign them. But yeah, no super clean way to do it
{
object[] _newArray = new object[inArray.Length + 1];
for (int i = 0; i < inArray.Length - 1; i++)
{
_newArray[i] = inArray[i];
}
_newArray[_newArray.Length - 1] = add;
//Return new array
return _newArray;
}```
Hello, this function creates a new array, and returns what I need it too, confirmed with debug. However: When I use it like this?
```items.Weapons = Astro_AddToArray(items.Weapons, _loadObj) as ScriptObject_Weapon[];```
``items.Weapons`` is simply set to an array of 0. Is there a reason why this is happening?
ScriptObject_Weapon is a ScriptableObject, also
- This is awful code.
- Is it set to
null, not 0? Becauseobject[]is notScriptObject_Weapon[]
Use a List, and almost never use object
Learn and rewrite that method using generics.
Or just use a List and use Add and don't do this at all
Yeah, it's set to null, actually
When we make a macOS build using il2cpp we get an null ref exception from within an automatic code signing process:
System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.)
---> System.NullReferenceException: Object reference not set to an instance of an object.
at UnityEditor.OSXStandalone.CodeSigning.HashUtils.WriteHashString(Byte[] data) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/HashUtils.cs:line 41
at UnityEditor.OSXStandalone.CodeSigning.HashUtils.HashFile(NPath file, Byte[]& sha1Hash, Byte[]& sha256Hash) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/HashUtils.cs:line 148
at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.SignResourceFile(FileToSign file) in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 243
at UnityEditor.OSXStandalone.CodeSigning.BundleSigner.<>c__DisplayClass9_1.<SignFilesWide>b__0() in /Users/bokken/build/output/unity/unity/Platforms/OSX/CodeSigning/BundleSigner.cs:line 193
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__272_0(Object obj)
This happens on 90% of our IL2CPP builds. (Mono builds succeed.)
We can't work out how to configure code signing. In this case we actually want to disable it so we can sign our own builds afterwards.
However I'm additionally curious what developer ID it is using to sign, since there seems to be no option to configure this in any way.
We're on Unity 2022.3.12
We can't reproduce this issue on a fresh project.
We've been struggling with this for days, any insights would be appreciated!
The docs also kind of contradict themselves here:
Unity automatically code signs any application it builds for macOS.
- Code signing & notarization
To code sign your application you need to use the command line. On your machine, open Terminal and navigate to the directory that the application is in.
- Code sign the application
That worked, thanks!
{
List<T> _newArray = new List<T>();
foreach(T item in inArray)
{
_newArray.Add(item);
}
_newArray.Add(add);
//Return new array
return _newArray;
}```
The code that worked
You can just do this:
var newList = new List<T>(oldList);
newList.Add(newElement);
Ah, actually in this case you should do this:
static void AddElementToArray<T>(ref T[] array, T element) {
System.Array.Resize(ref array, array.Length + 1);
array[^1] = element;
}
Then you can do:
AddElementToArray(ref items.Weapons, _loadObj);
Or:
static T[] AddElementToArray<T>(T[] array, T element) {
System.Array.Resize(ref array, array.Length + 1);
array[^1] = element;
return array;
}
Then you can do:
items.Weapons = AddElementToArray(items.Weapons, _loadObj);
What was wrong with just list.Add(...), why are we even using an array
dunno
the example was:
items.Weapons = Astro_AddToArray(items.Weapons, _loadObj) as ScriptObject_Weapon[];
Unless this is editor-only, this is a stupid premise, and if it is, then just use ArrayUtility.Add
Either they don't know that you can just use List<Weapon> and add to it directly, or they have a requirement to make a new copy rather than mutating.
I don't really like giving bad-code answers until those requirements are specified meaningfully. If they don't understand generics, I will go for the lowest common denominator answer
(Side note if it was already a list and you for whatever reason need to make a copy rather than adding directly, you can do:)
items.Weapons = new(items.Weapons) { weaponToBeAdded };
That's actually quite better, thanks!
I should also say why it's an array is because this is how I originally programmed it, without think I'd actually ever change it. Essentially, what's in the array at startup is the vanilla assets
This code is actually used to add addons using AssetBundle
It unpacks the items in an Bundle, and then checks what object is which, and if it's a specified object (Like Scriptobject_Weapon), it adds to the Item Schema
I guess that the reason I don't change to list is because it would break a lot of code (Which would take a while to debug and make sure works correctly, as I use this Item Schema a lot), and also because I would have to re-fill the list with the items, which there are a lot of lists and a lot of items to re-fill, which is time consuming
Like vertx said just use ArrayUtility.Add. I didn't realize unity had an implementation of this.
Honestly, me neither!
Anyway, I DID just use it like:
for (int i = 0; i < _originalArray.length - 1; i++){
items.Weapons[i] = _originalArray[i];
}
items.Weapons[items.Weapons.Length + 1] = _loadedItem;```
But it feels so cluttered, as I have to do this with maps, apparel, items, and more. I wanted to be able to just call a function
could also just use a list (use Linq to convert back to an array if needed)
I believe that's what I did in the code, here's what it's like for weapons:
{
items.Weapons = Astro_AddToArray(items.Weapons, _loadObj as ScriptObject_Weapon).ToArray();
}```
Thanks friends!
You can use pattern matching to further clean this up.
if (_loadObj is ScriptObject_Weapon weapon)
{
// You can use variable weapon now
}
Man, I never knew any of this before 😅
This will help me so much in programming
so, anyone know how to fix
Assets\script.cs(4,37): error CS0234: The type or namespace name 'Scripting' does not exist in the namespace 'Microsoft.CodeAnalysis.CSharp' (are you missing an assembly reference?)
What's the line in question? And prefferably the function it's in
It just means that you don't have the right dll.
You can inspect the assembly in visual studios to confirm that it doesn't contain the Scripting type.
where do i put the dll
Is it possible to add a string of information to an AssetBundle manifest? I'd like to use it to add an author's name
hmm
Assets\script.cs(11,38): error CS0117: 'CSharpScript' does not contain a definition for 'Evaluate'
Microsoft.CodeAnalysis.CSharp.Scripting.dll
Microsoft.CodeAnalysis.Scripting.dll
does winget install Microsoft.NuGet
hmm \nuget\Microsoft.CodeAnalysis.CSharp.Scripting.4.9.0-2.final\lib\netstandard2.0
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/11/2024 12:48 PM Microsoft.CodeAnalysis.Analyzers.3.3.4
d----- 1/11/2024 12:48 PM Microsoft.CodeAnalysis.Common.4.9.0-2.final
d----- 1/11/2024 12:48 PM Microsoft.CodeAnalysis.CSharp.4.9.0-2.final
d----- 1/11/2024 12:48 PM Microsoft.CodeAnalysis.CSharp.Scripting.4.9.0-2.final
d----- 1/11/2024 12:48 PM Microsoft.CodeAnalysis.Scripting.Common.4.9.0-2.final
d----- 1/11/2024 12:48 PM Microsoft.CSharp.4.7.0
d----- 1/11/2024 12:48 PM System.Buffers.4.5.1
d----- 1/11/2024 12:48 PM System.Collections.Immutable.7.0.0
d----- 1/11/2024 12:48 PM System.Memory.4.5.5
d----- 1/11/2024 12:48 PM System.Numerics.Vectors.4.5.0
d----- 1/11/2024 12:48 PM System.Reflection.Metadata.7.0.0
d----- 1/11/2024 12:48 PM System.Runtime.CompilerServices.Unsafe.6.0.0
Directory: C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget\System.Buffers.4.5.1\lib
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/11/2024 12:48 PM net461
d----- 1/11/2024 12:48 PM netcoreapp2.0
d----- 1/11/2024 12:48 PM netstandard1.1
d----- 1/11/2024 12:48 PM netstandard2.0
d----- 1/11/2024 12:48 PM uap10.0.16299
should i delete all the other lib dirs other than netstandard2.0
or can i keep them without problems
oof 526 errors
Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/rulesets already contains a ruleset file: Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/rulesets/DataflowRulesEnabled.ruleset. Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/rulesets/MicrosoftCodeAnalysisCorrectnessRulesDefault.ruleset will be ignored.
Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/buildTransitive/config already contains a globalconfig file: Assets/nuget/Microsoft.CodeAnalysis.Analyzers.3.3.4/buildTransitive/config/analysislevelmicrosoftcodeanalysisdesign_3_3_3_default_warnaserror.globalconfig will be ignored.
Failed to find entry-points:
Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' ---> System.Exception: Failed to resolve assembly 'Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in directories: C:\Unity_Editor\2023.2.3f1\Editor\Data\MonoBleedingEdge\lib\mono\unityjit-win32
C:\Unity_Editor\2023.2.3f1\Editor\Data\MonoBleedingEdge\lib\mono\unityjit-win32\Facades
C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget\Microsoft.CodeAnalysis.Scripting.Common.4.9.0-2.final\lib\net7.0\ko
...
error CS1703: Multiple assemblies with equivalent identity have been imported: 'C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget\Microsoft.CSharp.4.7.0\lib\netstandard2.0\Microsoft.CSharp.dll' and 'C:\Unity_Editor\2023.2.3f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Microsoft.CSharp.dll'. Remove one of the duplicate references.
i did
PS C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget>
nuget install Microsoft.CodeAnalysis.CSharp.Scripting -Version 4.9.0-2.final -Verbosity detailed
i deleted all dirs except for netstandard2.0
hmm
error CS1703: Multiple assemblies with equivalent identity have been imported: 'C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Assets\nuget\Microsoft.CSharp.4.7.0\lib\netstandard2.0\Microsoft.CSharp.dll' and 'C:\Unity_Editor\2023.2.3f1\Editor\Data\UnityReferenceAssemblies\unity-4.8-api\Microsoft.CSharp.dll'. Remove one of the duplicate references.
tho now i only have 1 error
hmmm if i move it into Assets - Unused and remove the .meta file then i get
Assets\script.cs(11,38): error CS0117: 'CSharpScript' does not contain a definition for 'Evaluate'
CSharp seems to be a namespace, not a type. And Evaluate seems to be in the Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript type.
yea
Press F12 when your caret is on the CSharpScript type and see what members it has.
And what assembly it takes you to.
Also it seems like there is no Evaluate. There's EvaluateAsync.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Microsoft.CodeAnalysis.CSharp.Scripting;
public class script : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
object result = CSharpScript.Evaluate("1 + 2");
Debug.Log("result = " + result);
}
// Update is called once per frame
void Update()
{
}
}
im doing this
from
Code Samples
Note: the samples require the following using:
using Microsoft.CodeAnalysis.CSharp.Scripting;
Evaluate a C# expression
object result = await CSharpScript.EvaluateAsync("1 + 2");
Don't you see any problems with your code?
Compared to the "from"
It's not the same what they have, is it?
await requires async method
Well, that's the only thing they have. So you've gotta use it
Make Start async. Or get the task result. That would make it execute synchronously.
finally finished evaluating
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
would i do object result = CSharpScript.EvaluateAsync("1 + 2").Result;
This is just a warning. That being said, you should probably do one of the things I suggested earlier.
Yes. That should work.
wouldn't this throw an error?
Because the async task won't have completed
or is it not actually async?
No. It blocks until the result is ready.
@fervent dagger is there anything specific you wanna achive with async methods?
code compilation
gotcha, are you looking for multi thread performance? if not I suggest using something like Unitask
Any idea why rider would see a source generator just fine, but Unity would show compile errors about members not existing as if the source generator isn't running?
(SG creates members in a partial class)
Ahh looks like there were compile errors.
Ahh, nope still not seeing it. Is there a way to debug this...?
Unity's example from the docs works fine. Just my code that isn't beeing seen by Unity.
Just tried manually doing it and all the code works. So it is just Unity not seeing it for some reason... 😕
If example works for you, then that means you probably have SG properly integrated and the issue lies in your SG code.
One thing with SG is that if it fails (eg throws an exception) there would not be any indication of it and the file just silently not get generated. There are ways to debug SG but I think VS is required (😒), instead a method I use is to try..catch your SG and generate a source file with the caught exception as comments in it, so you can inspect that in your IDE.
Some blind guesses without know the problem, are you doing file IO in your SG? Because that is not allowed.
Oh.. yeah I am reading a uxml file. It generates the code though and doesn't throw an exception (just tried with the try-catch as you recommended)
🤔
I'm fairly certain that file IO isn't allowed and that would throw, but now I can't be sure.
Well. I just commented it out and it works...
No idea why it isn't throwing though
Any suggestions about how I would go about reading the uxml then?
The mechanism for SG to read files is via additional files compiler argument (because SG runs on every key stroke in your IDE so doing file IO will tank your IDE performance)
But I think that would mean you need to add all your uxml files as compiler arguments though, and that sounds a bit yikes.
Can I add them to Addition Files some how? Is that a thing in the .csproj file...?
Via the compiler arguments in (IIRC) Unity project settings.
You'd also need to add them to your CSProj files though otherwise your IDE wouldn't know.
But yeah this is why I recommend to use SG only for generating code based on code, and generating code based on assets is probably better done with editor scripts.
😭
It is a pain, but I guess that is what I gotta do 😦
Thank you for the help! I am sure I will find other stuff to use source generators for.
Oh and I did more testing and yeah, in rider it generates the code from reading a file just fine. Evn seems to build. But in Unity, not so. No errors or warnings or exceptions. Just fails silently.
Interesting, I can't say if it's Unity or Rider that's being inconsistent.
A C# specific question, needed ASAP:
How do I call a concrete method of a class, when I am referencing it by it's interface, that happens to have a default method defined?
Did I get it wrong, or there still a big overhead when not caching the transform component of our behaviors?
Can I render alpha to the camera as a value? Im trying to get a custom render texture and I would like to capture alpha as value and not as a blend. Like the alpha channel of a render texture having data.
The idea is that I want to pass four values generated by a particle system texture (those 4 values being on the texture that the particle makes) by capturing it with a camera, and saving it to a render texture
I dont see the problem. Is the method only of the class and not of the interface?
concencputally my code should be something like this:
interface Iface {
string DoThing() => "iface";
}
class Concrete : Iface {
virtual string DoThing() => "concrete";
}
//...
Iface x = new Concrete();
x.DoThing(); // in my case it erroneously returns "iface" instead of "concrete"
A, a bad but working approach would be to cast it
Iface x = new Concrete();
(x as Concrete).DoThing();
but I can see how you wouldn't want that
an interface however, shouldn't have default methods tho, you would be better using abstract classes, or in the best case since we are in unity, a component based system. Can I ask why are u using interfaces for such a case?
My real case is much more convoluted (hierarchy of visitors, tree-like data structure etc). Basically I can't really know what concrete type the x is because it's passed in a parameter as an IFace
unfortunately due to some design decisions earlier I cannot easily move to abstract classes for now
smells like a very flawed design
best thing to do is to rewrite the whole thing and thank yourself later for it
yup, I im the middle of architecturing it and in the beginning of actually using the system
I can explain in more detail what I am doing and maybe it will give some more context, but the explanation could be a bit lengthy
Make a thread for it, and let's see
and im gonna bump this
for now let me explain a bit more, I know the design is far from perfect for now but I needed something between "prototype" and "perfect design" that I could iteratively refactor into something better
its not about perfect, its fundamentally flawed
also the part I'm doing right now is basically separate from the unity ecosystem, it could be a separate dll
ok, here it goes:
you should make sure you use the language features for their intended purpose and not overarchitect stuff with convoluted type-magic
The alpha channel is a value as much as any of the other channels. There's nothing that says it's what controls blending, unless you are using it that way. If you're sampling the texture and reading the values, you can read the alpha channel and interpret it any way you want.
Anyone knows how can I start implementing profile pictures of users in a list ex. leaderboards using firebase? I have no idea where to start
Like from steam?
What are some of the best Unity interfaces you guys use?
interfaces?
Sorry probably not making sense. Are there any unity interfaces. That let you tap into events that unity fires like whether that be from a collision, ui event, etc.
Unity does not work like that, it does not use interfaces to propagate events except for e.g. the IPointer interfaces
Lots of them, sure (with a loose definition of "interface"). Do you have a specific question?
It's not really productive to just list things. That's like reading the dictionary, it isn't going to help you learn.
Also you should probably be asking these things in #💻┃code-beginner
I was presuming interface in the strict C# terminology
Okay that seems to be where I am confused. Are there other helpful tools like IPointer
depends what you want to do
The entire scripting reference is full of "useful tools". https://docs.unity3d.com/ScriptReference/index.html
The question is way too vague without a specific objective.
Okay. I think to confusion is the terminology. What would you call tools like 'IPointer' and where could I find other tools like it?
Is this what you want?
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/SupportedEvents.html
IPointer is not a tool, it is an interface available from the Unity Engine
I'm still failing to grasp what you are actually asking for here
what do you mean when you say 'interfaces' because that has a very strict interpretation in the C# world
I'm asking for interfaces available from the Unity Engine.
It's kind of sounding like you just anything from the API
This feels more like a #💻┃code-beginner question
but what do you mean by interfaces, I think we are talking at cross purposes here
And you should be specific about what you want, not just generic "what is there", because you've been linked to the docs twice already, which shows what there is
The second link was for evenets you may be talking about
Do you know what a C# Interface is?
I was just asking if there are any interfaces I could use instead of re-inventing the wheel for my own game. I am currently using a interface that will help handle collisions, but I wanted to know if there are any other similar tools. I should've started off with that.
you still haven't answerd the question 'what do you mean by interface?' until you do this conversation is pointless
so which interface are you using to help with collisions?
One I made on my own. I can show if necessary.
An interface is a contract between the implementer (what you need to implement) and consumer (what has been implemented and allowed to use), interface by itself when removed from the two parties is not useful, so asking a list of useful interfaces isn't exactly a question that makes sense.
You will know when an interface is useful when 1) you see a consuming method asking for an interface, so you the implementer implements it, or 2) you the consumer want to be able to consume multiple implementations in the same way, so you create an interface for implementers to implement.
If you don't have either party, an interface is useless, and when you have one party, that party tells you which interface is used and thus useful.
please do
coz I'm struggling to understand what you actually are asking for
One moment
Scripts that need to react to a collision implement ICollisionHanderable
A CollisionHandler checks for the correct interface. If it has it then it sends a unity event to the corresponding script that implements ICollisionHanderable. Its not perfect, but do you guys find yourself commonly using specific Unity Engine Interfaces? I know you have to implement your own logic.
OMG, I honestly do not know what to say to that
Could you try?
it is quite weird to broadcast collision message to other guys by publisher-subscribers pattern
If you were somehow wrapping OnCollisionEnter in your own Interface it would have been interesting to see (which is why I asked), what you have done is the exact opposite which makes it pointless, redundant and unnecessary
May I ask why not? It's working pretty well right now. What issues will I run into if I continue down this road?
Ask yourself, in what way does this Interface enforce the implementation of OnCollisionEnter which it relies upon to actually do anything?
the whole point of Interfaces is to enforce a contract which can be seamlessly used
Sorry these are two completely different scripts. Is your perception that this is all under one script? Maybe this will help.
TriggerHandler checks the incoming collision object for a specific interface (Does_Damage). If the incoming object has that interface then it will fire off events on Damageable_Kart with info that Does_Damage returns
I have a bug that expresses itself on one specific device (google pixel 6). There's some massive jutter when doing various things - camera panning/zooming, typically. We're using Cinemachine. Since I can't repro this in the editor or other devices, what sort of things should I be looking at?
(I do have access to a physical google pixel 6, but .. honestly, don't know where to start in on this particular bug)
Why do you even need interfaces here?
"TriggerHandler checks the incoming collision object... if the incoming object has that interface then it will..."
Why cant that objects scripts just use the physics messages and do logic themselves? This looks like some massive over engineering to do with no benefit. It's just a bunch of extra events which arent free (relatively since the alternative is no events)
Dude I don't even know anymore. I just wanted to know if there were any Unity Engine Interfaces that you guys often implement in your games.
would like them to upload pics
oh if you want users to upload pics you would need to serialize them and store them i have done it before a long time ago but it wasnt super easy
I believe the existing unity interfaces are for UI stuff, I rarely use interfaces because most of the time it's just not needed. I find myself using abstract classes more because I want default functionality with variety.
Youd probably need to use this
https://firebase.google.com/docs/storage/
Steam would be the easiest if you're able to use it. 1 time payment to upload your game. Looking up and loading an image with steam is just a few lines of code.
Hello,
I have the following use case. I have a scene manager that handles loading screens between scenes, and also shows progress bars and what not.
Some scenes are only considered ready if there are multiple events raised (on world generation compelte, on player spawned, on music started playing etc.)
What is a clean way to check if all events from a list of UnityActions have been invoked?
(If there is one such pattern)
Keep them in a Queue or other collection and remove them as you invoke them?
Good idea, I think Ill do just that
thanks!
how can I hold a queue of UnityAction's regardless of their generics? <int>, <string> etc?
Thank you, I'll try it
If the queue is just for keeping track of what has already been called, then you don't need to know the type specifically, you can just use Queue<object>.
Or really, since it sounds like you don't care about the event order, a HashSet<T> can also work and semantically makes more sense. But even better, assuming an event can happen only once, you can just have an int to keep track of the number of event called and check if it has reached the total event count.
But maybe the scene should just have one big ready event for when it's completely ready, and listeners can just listen to that.
you might want a list tbh, if you want to not erase it as you iterate through it
Queue<object> sounds both correct and cursed imo
hmmm, you've given me a lot to think about, thanks a lot!
i agree with this. this is how I do it kind of
in my case, I have several delegates to coordinate level loading, so everything can go off at the right time
IEnumerator CoordinatedLoading(string filename) {
OnBeforeLevelLoad?.Invoke();
yield return null;
LoadLevelFile(filename);
yield return null;
OnLevelLoadEarly?.Invoke();
OnLevelLoad?.Invoke()
OnLevelLoadLate?.Invoke();
}
docstrings on each delegate detail the kinds of things expected to be happening during each phase. Like my tilemaps are changing during OnLevelLoad invocation. So everything that needs to happen on the raw level file happens OnLevelLoadEarly. Everything that modifies level goes OnLevelLoad, and everything that acts on the fully modified level goes OnLevelLoadLate
does that make sense?
this is a bit different from your question with respect to making a load bar, but this is how I coordinate my level loading
My names could use some work on that front tho
Not related the original question anymore, but I find stuffs like this to be very brittle. You are largely relying on convention to make sure the things are happening in the right order, and is one mistake away from creating a hidden bug that cannot be caught unless you notice it at runtime. In the future if you need to hook into one more thing, suddenly you need to make a new OnLevelLoadSuperLate or OnPostLevelLoad.
i had that until I made a clear distinction between what is allowed to go into each bucket
Which is still convention.
true i could have probably called the class manually, but it felt dirty
part of it is that I only established a convention after realizing what the pattern was to make everything work
eg the tilemaps changing is the critical moment where some things need to happen before vs after it
i believe the middle delegate only has one entry, iirc
which doesn’t make it right, but this is the pattern I only realized later
(and if I knew that was going to be the critical point, then I would have made that middle part differently, probably)
i feel impending danger
For something like loading, imo a much better pattern is to have each separate machinery that does just one thing and one thing only. That machinery could be a class, just a plain function, whatever, it does not matter.
Each machinery takes in some data (or takes in nothing), does some operation to it (whether that's changing the data that was fed in or creating data by itself), and spits out data in a new shape.
This way you let compiler enforce the loading for you: if a piece of machinery requires data from the output of previous machinery, you literally cannot execute them in the wrong order because the former wouldn't have the necessary input to start; if multiple pieces of machinery do not depend on each other's data, you can easily see that and turn them to run in parallel if needed.
This way you successfully turned your loading from convention based with no help from compiler, to something enforced by compiler to never be able to make a mistake.
that makes sense, but those parts of loading don’t necessarily have anything to do with each other, except for relationship to the middle part which edits tilemaps
And no issue with that, each part doesn't have to depend on each other and can be completely independent, but the point is by doing this you can easily see it: this machinery takes in no data so it's independent and I'm free to execute this in any order I want.
one example is a singleton that just takes a census of what was loaded into the tilemaps. And another is a singleton that just needs to know that it should clear its collections, because it’s about to be called
and neither of these functions require any arguments. it’s just a timing thing
a singleton that just takes a census of what was loaded into the tilemaps
That part is not independent, it very much depends on the tilemaps already being loaded.
And what's your way of ensuring that singleton is only executed after the tilemaps are already loaded? Nothing other than convention.
i mean, why would you subscribe a method to OnBeforeLevelLoad if you want to execute it OnAfterLevelLoad?
Exactly, that's entirely on the programmer to read the docs and make sure they understand which event to hook in order to do what they want. If they made a mistake, now the singleton will collect useless census data because tilemap is still empty, and you wouldn't notice that problem until runtime.
OnBeforeLevelLoad mostly notifies things to clear their contents before the level is loaded. So i don’t see how this could depend on anything? Without just adding a prerequisite that does nothing?
or adding an enum argument that clarifies what stage of level loading we’re on?
i guess I don’t understand how I would address your point without violating the Open/Close principle
You are missing the point, the point is that you are entirely relying on programmer to not make a mistake, where as if you have something like:
var tilemapCensus = new TilemapCensus(tilemap);
tilemapCensus.Execute();
You literally wouldn't be able to do it in the wrong order because you don't have tilemap loaded yet, it entirely eliminates the possibility of error because compiler is protecting you from it.
but that would require me to edit the code for level loading every time I add something that needs to go off when my level loads
which doesn’t sound correct
and a lot of those methods rightly contain no arguments
Loading and notifying is different though, there's nothing stopping you to still have a "level loaded" event only for notifying listeners (but not for listeners to hook into and modify the data, because that's loading)
maybe it’s best if I explain a bit more
the main script in OnLevelLoad that modifies the level basically goes into the tilemaps, and creates gameobjects based on tiles, and erases some of those tiles
OnLevelLoadEarly are methods that need to know that the level finished loading in its raw, unadultered state.
OnLevelLoadLate are methods that need to know that everything is now instantiated (so it’s safe to look at groups of gameobjects or tiles without their existence changing as a result of other things in the delegate)
naming aside, it makes sense as the functions within a given delegate must not affect each other in any way. I just lack a smart way to enforce that across like 15 singleston methods in a delegate
without making one giant cursed function to specifically orchestrate a specific order of calls
hello, i am loading a scene additively and async. the async handle shows a progress of 0.9f, yet isDone is false. what am i missing here?
Yes, and the smart way to enforce it is by leveraging the language and the compiler.
Nothing stops you from writing:
var levelTilemap = LoadLevelTilemap();
var dialogueData = LoadLevelDialogueData();
var enemies = CreateEnemies(levelTilemap);
var allies = CreateAllies(levelTilemap);
var dialogues = ProcessDialogues(dialogueData);
PositionGameObjects(enemies, allies);
Suddenly, if you attempts to call PositionGameObjects before enemies and allies have been created, you literally can't; or if you tried to create enemies without loading tilemap first, you can't.
On the flip side, it's immediately obvious that LoadLevelTilemap and LoadLevelDialogueData do not depend on each other (because they literally take in no argument) so you can parallelize them if performance is a concern.
Now you arrive at a system where the language and compiler enforces it for you, where there is no "early"/"late"/"pre"/"post" with conventions that programmers have to follow but no way to enforce.
that is normal behaviour, read the docs
oh fuck it's in the allowSceneActivation page, ive missed it. thanks a lot!
i think i see what you mean. my challenge is that a lot of these methods actually have no arguments
like if I want to make a singleton just .Clear all of its lists OnLevelLoadEarly, that function would only take in an argument if I artificially made it such, at which point i’m just playing with function signatures
That doesn't mean it has no argument, it very much does have an argument: it's just globally accessible.
wdym
my singleton might not need a reference even to the tilemaps to know to clear its own lists
Like if you have a function that does FindObjectsOfType<T>(), that function very much has a hidden argument, it depends on the objects already being in the scene.
These hidden dependencies is the reason you have to enforce a convention such that "X is already loaded before you can call this function"
how else to I make .Clear() ing private collections depend more forcefully then?
By not allowing you to use these hidden global dependencies, and enforcing each machinery is just "takes some data, fiddle with it, spits out new data" it makes the dependency chain clear, and thus able to leverage the language and compiler to enforce it for you.
If you are clearing some private data, then that's not part of the loading.
Key point here being private. If that data is later used by something else, then it's not private.
most of the contents of what is called is private
private, modifying private data
but that doesn’t mean it could not lead to some sort of actual dependency
Again you can still have an "level loaded" event, stuffs that do not matter to the loading can still listen to it and do whatever their own internal private data loading/cleaning as necessary.
i’ll need to think harder about this
The purpose of this whole thing is to ensure public data are always in the right execution order.
Like if something has some private data (private means literally nothing else can observe it) then it does not matter whether it was cleared in "early" or "late" or "pre" or "post."
If it does matter when it was cleared, then it means it wasn't truly private.
Hello,
I saw that it is good practice to keep functionalities on a per scene level. Persistent managers = 1 scene, Different menus = different scenes, different worlds = different scenes etc..., and to additively load them on demand when needed.
My question is how to handle things like EventSystems / Global volumes, which can only exist once per scene.
Thus, if i have a scene main menu for example which i'm working on, it needs a global volume + event system, but so does a deungeon scene for example. But when I additively load one or the other Unity will complain. I could only have 1 and DontDestroyOnLoad(), but I still need them when working on individual scenes, and removing them every time I stop working on a scene seems like a chore.
How do people handle this type of stuff?
One option is to not load additively
I see people be quite vehement about the modular scene method being the best + even unity's sample game chop chop uses it extensively. so im quite keen on trying it out.
I don't know how they do it, but I don't keep the main menu around when loading to gameplay scenes.
If you do need to load multiple scenes, I would probably either have a primary scene that makes sure to load the scene I need (even in editor) or to have scripts load those dependencies in every scene that needs them if they are missing
Like Gameplay mode scene would load the map scene
What is the best way to find another client's player object if you know it's id? Unity NGO
If you mean the network object id then https://docs.unity3d.com/Packages/com.unity.netcode.gameobjects@1.8/api/Unity.Netcode.NetworkBehaviour.GetNetworkObject.html?q=getNetworkobject
Thanks buddy. I will keep it in mind
This is how we handle our singletons https://pastebin.com/Cny1Yqt0 the even system for the ui lives on the same gameObject as our EventBus Singleton for example
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
can't enter playmode when this is uploaded
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
that's very interesting, thank you!
Usually I'll have a base scene with everything that's required and load and unload the other scenes on top of that.
yea but how do you work on those scenes individually, since if you run those scenes from the editor, you won't have the dependancies? so im curious how you manage that aspect
Oh, when you press play you mean?
Your can add multiple scenes in the editor
oh damn i did not know that
what a simple solution
thanks!!! ❤️
Or you can write an editor script that listens for the play event
And loads the base scene
There's an event for entering play mode and you can load any scene that you need when you hit play
thank you very much!
If you want to add this you can use the initialize on load attribute on a static class and subscribe to the play mode change event. Then you can use the editor scene manager to check if the scene you want is loaded and load it additively if not
where do i get this from
Assembly 'Assets/nuget/Microsoft.CodeAnalysis.Workspaces.Common.4.9.0-2.final/lib/netstandard2.0/Microsoft.CodeAnalysis.Workspaces.dll' will not be loaded due to errors:
Unable to resolve reference 'SQLitePCLRaw.batteries_v2'. Is the assembly missing or incompatible with the current platform?
Reference validation can be disabled in the Plugin Inspector.
0 packages returned for SQLitePCLRaw.batteries_v2
so far i has all these
I need some help on getting a method called after a domain reload. I have some data that is private and instantiated through a method, but after it reloads the domain, the data gets lost
How could I get that method called again after the domain reload is finished?
I guess I need to do something seen here? https://docs.unity.cn/es/2021.1/Manual/DomainReloading.html
Domain Reloading resets your scripting state, and is enabled by default. It provides you with a completely fresh scripting state, and resets all static fields and registered handlers each time you enter Play Mode. This means each time you enter Play Mode in the Unity Editor, your Project begins playing in a very similar way to when it first star...
You probably want to use the InitializeOnLoad Attribute
https://docs.unity3d.com/ScriptReference/InitializeOnLoadAttribute.html
have this in your initializer. Note it's edit mode only
AssemblyReloadEvents.beforeAssemblyReload += BeforeAsm;
AssemblyReloadEvents.afterAssemblyReload += AfterAsm;
Weird, it doesn't get called
private void Start() {
#if UNITY_EDITOR
AssemblyReloadEvents.afterAssemblyReload += Test;
#endif
}
void Test(){
Debug.Log("you called me?");
}
have this, and doesnt seem to be called
also this class has a [ExecuteInEditMode] attribute to also be called on edit mode
the before one does get called, but not the other one
Start isn't going to be called at edit time afaik
With the [ExecuteInEditMode] it does when loading the scene, which is when it should subscribe to the event
Well, ended up doing a combination of OnValidate, OnEnable, and Start with some events, it sounds way more complicated that what it actually is. But i didnt really need to reload after assembly really, but after something else is called. So endedup doing it with events
I need help, the next code it's supposted to save another boxhelp height on boxHelpHeight var, that works correctly, cause the log shows me the values changing... But when i try to apply the var's value to the right boxhelp it doesn't work... What could happen? The right boxhelp changes it's vertical size to a really small one and it doesn't do nothing with that code```csharp
boxHelpHeight = GUILayoutUtility.GetLastRect().height;
Debug.Log("BoxHelp Height: " + boxHelpHeight);
// RIGHT BOXHELP
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(boxHelpHeight), GUILayout.Width(EditorGUIUtility.currentViewWidth * 0.25f));
GUILayout.Space(2);
GUI.backgroundColor = new Color(46f / 255f, 204f / 255f, 113f / 255f);
propertyAdditionMenu.Draw();
GUILayout.Space(15);
GUI.backgroundColor = Color.white;
EditorGUILayout.EndVertical();```
how do you guys handle async event handlers? how do you unsubscribe an async event handler from an event?
It should be the same as sync, what's the issue that you are having?
if I subscribe with an async function I cant unsubscribe because afaik you can only subscribe with an async lambda. the internet consensus seems to be to only use async event handlers if you never want to unsubscribe, but i wanted to see if someone has a solution
You certainly do not need to subscribe with a lambda, and even with a lambda you can still unsubscribe it.
you can't unsubscribe with lambdas in any case
unless you save the lambda to a variable
A lambda ultimately just compiles down to a C# method (with a capture class) anyways.
So you can do either:
- Save the lambda to a variable, subscribe/unsubscribe that variable.
- Write it as a method rather than lambda, subscribe/unsubscribe that method.
I think even then there are dangers: https://stackoverflow.com/a/41199095
you can not subscribe with an async method
No, no danger
that's just saying not to use lambdas
as mentioned
saving it to a variable works to unsubscribe if you keep that reference around outside the function
e.g. in a member variable
It has nothing to do with async
oh okay, understood. thanks a lot! will do that then
I would just avoid lambda entirely to make it simpler
but i cant subscribe with an async function otherwise or can I?
Wy not?
Seems to work fine?
You absolutely can subscribe with async method, because lambda is literally just C# method.
ah damn, okay, sorry guys i mussinderstood it seems. thanks a lot for your help guys @scenic forge @sly grove
does any one have any experience with making melee combat ?
im trying to make tomething like this
i dont want to make it using raycast cuz of that i had problems with blocking
ooo
Start
UnityEngine.Debug:Log (object)
script:Start () (at Assets/script.cs:9)
evaluating ...
UnityEngine.Debug:Log (object)
script:Start () (at Assets/script.cs:10)
result = 3
UnityEngine.Debug:Log (object)
script:Start () (at Assets/script.cs:12)
Debug.Log("Start");
Debug.Log("evaluating ...");
object result = CSharpScript.EvaluateAsync("1 + 2").Result;
Debug.Log("result = " + result);
Thinking of ways to do characters in my top down dungeon crawler. Came up with this idea so it can happen in runtime, but not too sure about it yet, still trying to wrap my head around how to do attacks. Any advice?
I just don't really know where to start with something like this
Hey guys, I came across an interesting problem and I didn't know what channel to post it in so I'll put it here 😅
While testing my game, I noticed something weird was happening with the player taking damage. Normally he does take damage fine but when the player presses the attack button right before he gets hit, he doesn't take any damage.
I double check the collision I had in the code but nothing was out of the ordinary. I have a interface called IDamageable that is currently on the Player Health and Character Guard script. I checked to make sure it wasn't accidentally grabbed guard script but it said (Debug.Log) said it was the parent GO which the guard isn't on but the health 😭
In the Console screenshot, you can see it grabs the first one four times and the second one twice. I'm not sure whatsoever what the problem is, DEFINITELY need another pair of eyes!
Thank you in advance!
maybe the attack's collider is interfering with the player hitbox?
unless the attack doesn't use colliders
Hello!
I've had a problem since upgrading unity recently, my custom build script fails because it tries to copy the built data somewhere after the build except the data isn't there yet
After calling BuildPipeline.BuildPlayer , if I list the contents of the directory, I get every PDB and EXE, but the directories (MonoBleedingEdge and GameName_Data) are not there yet. They show up a few seconds later... This behaviour did not exist in Unity 2020: after calling BuildPlayer everything would be guaranteed to be there, now it's no longer the case
What function or event should I usee or subscribe to, to run code after the build has been completed and every folder/etc created?
@cerulean sky There is also the C# FileSystemWatcher class which may be use if the above does not work
I don't get it, can you explain it to me please? I implemented the interface in my build script but it does nothing, the callback is not called
show your !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ah got it, there was a priority int to implement aswell. Thanks 🙂
is here anyone that can help me to implement octree for my terrain system?
you didnt tell us what are your problems....
Does anywhere here worked with LLM unity from GitHub?
hi i need help .. can anyone suuggest what script or method can i use for saving collect gamobject in level and display on another scene
Class/struct/fields on a static class is probably the most straightforward way to accomplish this.
Is there any way I could pass additional mesh data to the shader without associating it with the mesh vertices? My use case is, I'm rendering a voxel mesh and would like to pass an array of voxel ID's for the chunk to the mesh shader instead of storing voxel ID's inside each vertex
You can look into https://docs.unity3d.com/ScriptReference/Material.SetFloatArray.html or similar function.
Right, with settings a buffer of sorts inside the shader
My next question is, each chunk will have a unique set of blocks obviously, which means that buffer in the shader will need to be unique for each chunk
So how can I have that buffer property be per-instance?
How do I correctly generate shader and material in the runtime?
what I have currently (simplified):
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[DisallowMultipleComponent]
[SelectionBase]
[ExecuteAlways]
public class SdfSceneController : MonoBehavior {
[SerializeField] private Shader? shaderAsset;
[SerializeField] private Material? materialAsset;
private void OnValidate() {
if (shaderAsset == null) shaderAsset = ShaderUtil.CreateShaderAsset("// empty shader");
if (materialAsset == null) materialAsset = new Material(shaderAsset);
materialAsset.name = shaderAsset.name;
}
protected void OnEnable() {
Renderer = GetComponent<MeshRenderer>();
Renderer.sharedMaterial = materialAsset;
}
public void RebuildShader() {
var shaderText = AssembleShaderSource();
Debug.LogFormat("Shader code:\n---\n{0}\n---", shaderText);
ShaderUtil.UpdateShaderAsset(shaderAsset, shaderText);
}
// + custom editor with a button for calling RebuildShader() method
}
and when running in editor and clicking RebuildShader it spams:
State comes from an incompatible keyword space
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
but when I run play the shader is generated and displayed correctly
At runtime? Afaik you can't.
ShaderUtil is in the Unity Editor assembly
maybe not in runtime, but in the editor so that the asset is not stored in project files and is only temporary when object is loaded or something
hmm, I think I would like to sometimes regenerate a shader in runtime when the game is actually playing
is it not possible?
I would be very wary about doing anything that isn't just basic maths in OnValidate
at least update their code
this was a temporary workaround to update in the editor both shader and material when something in project changes. Which way coud I use to always make sure (both in editor and in runtime) that my script always have generated and up to date material and shader on itself?
If you're doing anything more then that I would delay the functionality using EditorApplication.delayCall
Where would I add to that delegate?
In OnValidate, so you move the functionality to the actual editor Update where there are less restrictions (might also have to check whether you're currently deferring to not double-up)
I'm not a coder but I have a question that will probably have an advanced answer, and I'm not hopeless so I'll be able to probably understand the answer on a basic level enough to convey what needs done.
So preamble aside,
We are trying to munge multiple meshes from modular level design into larger single meshes, the current solution however had code munge multiple parts of scenes causing them to no longer be able to be edited.
Is there a way to tag things to munge or auto munge at the time of compiling/baking the game instead of in the scene files? So this way only the RC gets munged levels and the master scene files remain fully modular?
If it's just for optimization purpose, unity static batching would do it for you automatically. Otherwise, you could hook to the build pipeline to perform preprocessing before the build.
Having an issue with our build server where we get these errors after restoring the cached Library/ from an older buidl:
error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkCompiler/ParsedHierarchy/Sequence.cs' could not be found.
error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkCompiler/CharacterRange.cs' could not be found.
error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkRuntime/VariablesState.cs' could not be found.
error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkCompiler/ParsedHierarchy/Choice.cs' could not be found.
error CS2001: Source file 'C:\Users\runner\actions-runner-es\_work\enter-the-chronosphere\enter-the-chronosphere\project\Library/PackageCache/com.inkle.ink-unity-integration@1.1.7/InkLibs/InkRuntime/Flow.cs' could not be found.
The issue seems to be that it's looking for verison 1.1.7 of the package, but we've since updated to 1.1.8. The error doesn't give more info about where these old file paths are referenced though.
I would expect everything to be updated by Unity before it started to build.
Having an issue with our build server
Is anyone kind enough to help me on this Android build error? It's been 2 hours now that I'm trying to solve a build problem on Android, ChatGPT can't help me. I have this error on build :
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
FAILURE: Build failed with an exception.
Where:
Build file 'E:\Unity\Unity_Projects\WEGames_1_MagicGrid\Library\Bee\Android\Prj\Mono2x\Gradle\unityLibrary\mobilenotifications.androidlib\build.gradle' line: 5What went wrong:
A problem occurred evaluating project ':unityLibrary:mobilenotifications.androidlib'.
No signature of method: build_3ny7gyewinvf307n5slubpz6h.android() is applicable for argument types: (build_3ny7gyewinvf307n5slubpz6h$_run_closure1) values: [build_3ny7gyewinvf307n5slubpz6h$_run_closure1@64ca58f0]Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Here's my gradle file:id 'com.android.library' } android { def unityLib = project(':unityLibrary').android // Use 'android' instead of 'extensions.getByName('android')' compileSdkVersion unityLib.compileSdkVersion // Directly use the compileSdkVersion property buildToolsVersion unityLib.buildToolsVersion defaultConfig { minSdkVersion 22 consumerProguardFiles "proguard-rules.pro" } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } bundle { language { enableUncompressedNativeLibs false } } } dependencies { api files('../libs/unity-classes.jar') }```
@untold moth I can't find the original thread but someone from Microsoft emailed me back and we were able to diagnose the VS/Unity hang I experienced before. Turns out you can still deadlock yourself if you're creative. As a "general warning" to whoever reads this (not sure where this nugget of information should best live.. a github gist?):
If you put a breakpoint on a line of code that a debug watch expression tries to evaluate (in the course of hitting that breakpoint), VS and Unity will hang pretty hard (deadlock/race condition). It's not as unlikely a scenario as you might first think - since if you use watch expressions to get to the bottom of a bug, you're likely to also have breakpoints "around" that functional area, deadlocking yourself out of your tools.
In my case, something was going wrong with my player loader, so I had a breakpoint at the beginning of the load command - but I had previously put a watch expression to show me the value of something in that player structure - which was also trying to load the player through the load command. The debugger and VS were competing and stuck on the same breakpoint. So uh.. don't do that. 🙂 Watch expressions are great but in visual studio, don't seem to play nice with breakpoints or conditional breakpoints.
Ah, that explains it. It's basically the same as a race condition/multithreaded deadlock as the evaluator runs on a separate thread/process(or it injects the code, but the injector is on a separate thread? Not entirely sure). I generally try to avoid calling methods in the expression evaluation feature or not use it at all.
It tends to slow down your app considerably too, even if you don't run into a deadlock.
I think I am working on same thing right now and I have done some of that thing already 🙂 A bit different thing, but still pretty much the same
I have done it like russian doll: Player prefab holds the scripts about movement and control and has a placeholder for actual character. Then character prefab is being instantiated in that placeholder. Character holds the scripts with stats and skills and so on and also has the placeholder for character 3d model. (In my case this is a must since I plan to switch the controllable characters and also to be able to swap models of those characters). I am still working on skill scriptable objects and still have no idea how to implement this so I am kinda stuck with this and switched to working on something different )
Yeah I don't often use the expression evaluation in the watch window, but in this case I was needing access to a private member through a singleton so I did.. not realizing/remembering that evaluation of that expression would go through a breakpoint (and that's what broke). Conditional breakpoints and evaluated watches are really slow on performance, but sometimes they're the best way [for me] to find a buggy and spray it 🪳
I have implemented a generic class to keep a runtime collection of some stuff with some methods (GetAll, GetById, Add, Remove, etc.)
Collection<T> where T:MonoBehaviour
First, have you defined something like it and second, in Get method, do you prefer to return the gameobject or T itself? Another question, which component of that gameobject/entity should be chosen? Because a gameobject contains several different components
what is the underlying Collection of your Collection?
btw you should always return T because T will give you gameObject but GameObject will not give you T
You can write some method eg query by gameobject if you need all monbehaviour of one gameobject in your collection
Btw get components mono behaviour can also do that, though it may return some scripts that not in your collections
but GameObject will not give you T ?!
gameobject.GetComponent<T>
The benefit of returning gameobject is that you can access components easily
How do you choose which component is the main/entry for a gameobject, so use it in spawn time or getting a gameobject through collection, etc.
That is GetComponent giving you T. The whole point of caching is not to have to use GetComponent
Caching is not my problem at all. It is pointless and meaningless in those situations I explained like spawning or getting from a collection
Callers can cache if they want
then what is the point of your collection at all?
I think i know what you want, you have one mono behaviour and you want to get other mono behaviours
I said keeping a runtime collection
For example a list of items, enemies, characters, buildings
No
you make no sense, you want a runtime collection but you dont want to cache, why?
public class Collection<T> where T : MonoBehaviour
{
public event Action<T> Added;
public event Action<T> Removed;
protected readonly Dictionary<Guid, T> ItemDictionary = new();
public int Count()
{
return ItemDictionary.Count;
}
public T GetById(Guid id)
{
return ItemDictionary[id];
}
public bool TryGet(Guid id, out T item)
{
return ItemDictionary.TryGetValue(id, out item);
}
public IReadOnlyDictionary<Guid, T> GetAll()
{
return ItemDictionary;
}
public IReadOnlyList<TType> GetAll<TType>()
{
return ItemDictionary.Values.Select(item => item.GetComponent<TType>()).Where(item => item != null).ToArray();
}
public void Add(T item)
{
ItemDictionary.Add(item.GetComponent<Entity>().InstanceId, item);
RaiseAddedEvent(item);
}
public bool Remove(T item)
{
return RemoveById(item.GetComponent<Entity>().InstanceId);
}
public bool RemoveById(Guid id)
{
var removed = ItemDictionary.Remove(id, out var item);
if (removed)
{
RaiseRemovedEvent(item);
}
return removed;
}
protected virtual void RaiseAddedEvent(T entity)
{
Added?.Invoke(entity);
}
protected virtual void RaiseRemovedEvent(T entity)
{
Removed?.Invoke(entity);
}
}
WTH, 🙂 you said T is better. I said returning GameObject (Get method) is OK completely
public GameObject GetById(Guid id)
{
return ItemDictionary[id];
}
My concern is if a component of a gameobject is the main component and other classes work with it instead of gameobject itself, how do you consider it and select that component?
"main component" ?
Hey, I'm converting a byte that I get from a packet into an Enum using the code below:
reader.ReadByteSafe(out byte messageType);
receivedType = (MessageType)Enum.ToObject(typeof(MessageType), messageType); ```
Question: my `MessageType` currently has entries 0-3. What would happen if the byte received would equal 4 or any different number?
Would it throw an error or just create an invalid enum?
Nevermind, looked it up (shouldve done so in the first place) - apparently just has the enum represent a value equal to the int behind it 🤔
you have tested it
enum ABCD{
A=0,B=1
}
public static void Main(string[] args){
Console.WriteLine ((ABCD)2);//2
Console.WriteLine ((ABCD)1);//B
}
I'm putting some of my game through a bit of a stress test for performance tuning.. but I'm not sure how to really proceed with the profiler. Here's a snap of a slow frame during the test.
It appears as if a lot of time is taken up with instantiate calls. Would pooling objects be a good way to reduce those calls?
here's a zoomed in instantiate.. there's a lot of textmeshpro items, but I don't know a way around that (we show little popup texts for score at the point of the score)
what's the stuff to the left of the instantiate
that's taking up about equal time to the instantiates
same with the stuff on the right
a lot of logic
well maybe that logic can be optimized
In a nutshell, it's a grid based game with a bunch of tiles of different types, and they all have various properties that determine how they move, interact with other tiles, destroy themselves or other tiles, etc
It probably can, but .. it's also just an awful big stress test .. lemme snap a quick vid
I'd zoom into that stuff and see what's slow - it can likely be optimized
A "typical" level followed by the stress test level
The way I'm handling the logic now is to essentially recursively move each piece one at a time until it stops moving.. It could be changed to be smarter, but it turned out to be ridiculously complicated as I started to add tile types (like a tile that is destroyed by something moving "through" it but not stopping the original), or level shapes that aren't just grids
I don't think the 13x13 with 50+ tiles on the board at once will ever be a part of the final product.. I'm a little hesitant to try to poke at the premove and executemove parts of the method
They appear to be about 33% of the total processing time of that frame which seems ok
I am using a fair bit of LINQ in there though, maybe I should go to more traditional loop/finds
Actually, on the worst frame (one of them hit 625 ms) the game logic part of the frame is still small.. I don't think it's a great place to try to optimize
yeah looks like your ExecuteMove function is really slow
the execute move has the instantiates
doesn't look like it
Looks like you're doing ToList a lot too
that's going to be very inefficient/create lots of garbage
Oh, sorry, you're try - it's in EndTurn()
Yeah, I think I could probably reduce the LINQ use
Lemme paste a couple snippets
reducing/eliminating recursion will most likely help as well
there's nothing you can do with recursion that can't be accomplished with a Stack or Queue
yeah that switch is pretty inefficient
I folded up a lot of the code to hopefully make it readable, but this should give the gist - recursively move each tile one space at a time
especially since it seems like that code is probably running many times when it could be running once and the results reused?
I don't think that matters - that particular switch only happens once per move.. I think the optimization would be in TryMoveOnce() since that happens 10,000+ times
wait, which switch?
in Premove()?
Premove orders all the tiles (since they have to be processed from "frontmost" to back), then iterates over each, doing "tryMoveOnce()" until the tile is done moving
this is a 1024 game?
imagine an array like this: [ ]=[ ]=[ ]=[ ]=[ 1 ]=[ ]=[ 1 ]=[ ]=[ ]=[ ]
the "1" on the right moves first until it hits a wall, then the "1" on the left moves until it hits the other tile (which is now at the wall) and then they both merge into a 2
yeah, it's a 1024-ish game
but my spin on it is a lot of custom tile types
etc
Ok. Yeah I'd have to think a lot about the most optimal way to do this. What are all these ToLists from in the profiler if not Premove?
the tolists are probably in the TryMoveOnce - I folded up all those "ifs" but a lot of them are doing shit like this:
ie - using where in LINQ instead of for'ing over the collections
I'm assuming (or recall vaguely?) that .Where() has an implicit ToList
Should I look at using something like BenchMark.NET for this? I'm .. having a hard time sorta telling where I should spend my optimization energy
Like, I can't tell from the profiler what the "sum" of a given method execution time is over several frames.. i can peel apart one frame but it's hard to get big picture from this
well all of this is is one frame, no?
Don't we really only care about one frame at a time?
true
over several frames sum isn't really that relevant
it shouldn't... can you zoom in on that and show what function the ToList is inside?
I also see a really high amount of GC use.. is that.. actionable..?
It definitely still creates an IEnumerable though
sure, one sec
definitely - Linq is a big culprit here
oh wait, nevermind, i mixed up the colors, it's "other"
the puke color of "others" is too close to the brown of GC
is there any tip you have to make this profiler hierarchy a little easier to read/navigate? not exactly sure what I'm looking for but it's a little hard to navigate
here's the whole frame
lemme try to notate it
I usually look at the profiler hierarchy, I think that's what it's called. You can sort by allocs or time in ms.
like this?
Yes that's what I look at
Expand it even further, itll eventually tell you GC.alloc and anything else that's causing issues
For the big areas
so basically EndTurn, Premove, and ExecuteMove are all roughly taking 1/3 of the frame, so at least I can peel apart each of those and figure out the best way to optimize
cooooool, this is much better
Yea linq and instantiate seems to be decent problem areas
so firstOrDefault is taking a bit of time, 15 ms.. i could optimize there, instantiate takes 23ms, don't know what I can do to optimize that
my initialize function is also taking 11ms which is surprising to me
that should just be trivial
hard to see any obvious optimizations here, now that we're getting down to the 1-5ms amount, but I do see that I've left the UpdateDebugText() in there, and the ToString() can probably be cached or optimized, that shouldn't take 2ms.. etc..
anyway, this is actionable now, thanks
this is also cool since it already shows me what I thought I needed from Benchmark.NET - the total amount of calls in the recursion
tryMoveOnce only called 318 times.. much less than I would have guessed
oh wow, i found a super easy thing to fix..
basically in the "try move once" (the 318 calls) I check to see if there's anything in the destination by iterating the entire grid until it finds something in that location instead of caching/storing items
yep
keep going like that
I see a lot of your code seems to be iterating the whole grid
making a hashset of tiles on the grid and then looking up their positions will be much faster... or alternatively i could tackle the frog of just making the GridPoint (a custom struct with an X and Y) implement the appropriate interfaces to be used as a key itself.. so I could TryGetValue on that key instead of iterating an entire dictionary of 13^2 items 318 times
revisit whether that's always necessary
yeah - in general I tend to not optimize logic like this because it's often not necessary, and with all the tile types and "domain logic" of my game, making these methods more readable and less bug prone is important to me
but this is a totally acceptable/easy fix.. like 2 lines of code
should take 40ms off of the frame
You could try to preload the resources. Usually, putting the texture in memory is what takes a really long time for instantiation.
these objects aren't unity objects
just naked classes
I even wrote an API on this grid to prevent myself from doing stupid shit
Why use Instantiate then?
so I don't even need to change anything on the unity side, I can just cache these items and rebuild the cache manually or whatever
Strange, I would have expected to see some instantiate there and there. At least, this is what the profiler looks like.
the game client needs to instantiate the tiles after all the processing is done
Those properties are convenient but will be inefficient if used a lot
those OfType things
yep, that's what I'm changing
I don't mind a little extra data use here - caching some of the various types
it makes the logic a bit easier to read but .. yeah, doing the oftype or firstordefault repeatedly/recursively is clearly slow
it lets me write code like this, though, which I think is bug-resistant because it reads a bit like english:
and all my tile classes have the abstract/polymorphism/interface thing going on to implement their own behaviour (and nothing else)
but then as a side effect, i need quick ways to get sets of tiles with some qualifier at the grid level, like "all destroyable tiles" or "all mergeable tiles" or "all number tiles" or whatever, and building that on the fly isn't cheap
There is nothing wrong with doing that. Code should be self explanatory.
what do you guys like the API for something like this to look like? I don't use this pattern often (where I give the power to rebuild the cache externally)
looks fine.
something like that
I would personally use the TryGet Pattern rather than a Nullable but I'd say that's a matter of preference.
Hm.. I feel like there was a reason I adopted this pattern.. maybe something to do with blazor/razor and nullable types .. but I can't recall
I do like the tryget pattern better overall
I am not really fan of nulluable as well.
I also really like the proxy pattern. (for everything cache)
hello, i am loading some scenes additively when needed in the editor via the EditorApplication.playModeStateChanged event.
but after doing so and leaving play mode, the additively asdded scene gets removed. is there any way to keep it there? (additively added to my scene, just like if it were drag and dropped there by me)
TryGet(out) pattern is better than nullable imo
every time I try returning null for a fail state, it just leads to spaghetti
Not a code question, ask further questions in #💻┃unity-talk if needed.
Your font hasn't been processed properly
and what can I do?
ask further questions in #💻┃unity-talk if needed.
I think I agree - I have a client that uses the Response<T> everywhere and I hate it. ie:
// Least favorite
public ResponseType<T> GetPlayer(int id); // return type has like.. .Ok and .Error and .Warning along with T
public T GetPlayer(int id); // throw exception? return null?
public bool TryGetPlayer(int id, out T player);
Using null to represent failed state is fine if you have NRT turned on. The problem with using null to represent failed state isn't that it by itself is a bad idea, but that C# type system does not help you keep track of it, unless you turn on NRT. In languages with type system that was built with that in mind, it's hardly a problem and try pattern doesn't need to exist. (Try pattern also has some minor ergonomic issues both for the implementer and the caller)
State of null in C# is generally quite unfortunate and especially worse in Unity. I did migrate to NRT a few weeks ago and it does feel worth it, but the process was painful.
the "billion dollar mistake", indeed
if I have an event being raised in a file somewhere in an addon, let's say /Assets/Plugins/Foo/bar.cs invokes a UnityAction<int> in a class called Baz and a method called Bat. Is there any way I can override that from a script inside my scripts folders, so that when I update the unity package, my change doesnt interfere with the update?
PS: i must do this because the package in question raises an event, while I need it to raise an event that is encapsulated in a scriptable object so that i can share it between scenes
listen to the event from your custom class/SO and refire your own event.
but the script listening for the event is in another scene.
That's not really an issue. Propagate the reference however you need to and refire the event from your SO
Isn't the point of your SO to bridge such reference gaps?
Have that script reference the SO to inform it about the event being fired.
Yes, it is just not clear to me how to fire it
I'm trying to process what you wrote here but I'm not sure I understand
What part exactly?
basically how would I fire the SO event from my own script in scene B, without having to overwrite the asset script itself
Declare an event in the SO and fire it. You need to subscribe to to it from whoever wants to get the forwarded event
Original event -> SO -> SO event -> listener
Or rather original invoker -> call a method on SO -> SO invokes an event -> listener
Or rather original invoker -> call a method on SO.
This part is the thing I don't know what to do. Because it's invoked my a unity asset from the asset store. I don't want to go into the script and manually call it because when updating the asset I imagine it will get lost. I also don't want to keep track of 100s of changes I do in each of my assets. So how do I achieve this?
Then make another proxy in the scene. Listen to the event from the asset and call the method on the SO.
Or maybe avoid the SO entirely..? Are both scenes loaded at the same time?
no, loaded based on some events at sepparate times
okay thanks a lot, that is actually a good enough solution for me
So the event that you want to forward is not at real time..?
it is triggered after terrain generation is complete, a few seconds after the scene is loaded
And you want to listen to it from where?
a "persistent managers" scene, that contains a scenemanager
that one handles the loading screens / progress bars, so it needs to know when the loaded scene is ready to be shown
Ah. Is it a DDOL scene?
no
How are they persistent then..?🤔
or sorry, if you mean metaphorically then yes
i imagine scenes cannot be ddol-ed right?
No. But when you make an object DDOL it is moved to a DDOL scene automatically.
ah okay. the GO's within the persistent managers scene are not DDOL, but the scene itself I one I just keep around for all scenes basically
the reason I don't ddol the managers inside yet is because im not sure whether ill need them for ALL scenes in the future
So you're loading other scenes additively?🤔
yes
I see.
Anyways, if the managers are always present, you probably don't even need an SO. Just call a method on your manager from the proxy script.
ah, you're right
but for some reason I like the event re-invokation option a bit more
seems like it's a bit less tightly coupled
@untold moth thank you very much for your patience and great answers
To be honest there's nothing advanced about that question though. Maybe ask in #archived-code-general next time.
will do!
Hey! I'm trying to forward my camera feed to my locally running python server, how would one go about sending/extracting the camera feed?
Instead of streaming the video do I have to send it frame by frame? I understand all the websocket stuff I'm more curious about the Unity side of things since I'm a beginner
What's the goal here exactly?
I want to use OpenCV in a way where the video feed it receives comes from my unity app instead of a physical webcam
afaik opencv requires frame data not some compressed stuffs, that mean you have to feed it with frames, btw isnt you still need a phyiscal camera?
dont know python, so difficult
There seem to be some OpenCV related assets on the asset store - not without a cost though
Is the python server running on the same computer and guaranteed to always be?
You could try reading the texture data directly from GPU memory
open cv is written in cpp so you may write a plugin without any network traffic
Nope, I intend to use it instead of a physical camera
Yeah, I'm using the python wrapper because I've never written a line of cpp, so that's kinda out of the question
I mean it can't be that hard right? I'm reading the code of flightmare simulator which is a quadcopter/drone simulator that does the exact same thing, where in unity the video is exported and is passed into computer vision software
This is a code snippet, there seems to be a render method where a Texture2D is created
What exactly is that? Is it an in image, or what exactly?
So this is a really wierd question, but would it be possible to compile shaders during a game’s runtime?
Rather than at build
In what sense exactly? Are you looking for the ability for users to drop their own .hlsl files into a folder for import or something? Or are you just looking to distribute shaders in Asset Bundles?
The former, more or less
If that's possible it will be very difficult. The Unity core engine definitely doesn't ship with a shader compilation pipeline built in
You want to make ShaderToy more or less?
Fully aware it’s not practical lol
No idea what that is
I’ll look into it
One sec
realtime writing shaders and visualizing them immediately
really fun web app 😛
Sort of, id still like to be able to apply them to materials and such
The closest you can get to runtime compiled shaders is to write a native graphics plugin to submit commands directly to OpenGL/DirectX/Vulkan. But that bypasses Unity's Shader/Material system.
I have a custom mesh, which is a cube, how can I get the center position for one of the faces? I can do it with a unity cube but not a custom mesh. The gizmo will spawn inside it. With Unity primitive cube: Vector3 spherePosition = transform.position + transform.right * transform.lossyScale.y / 2f; Gizmos.color = Color.yellow; Gizmos.DrawSphere(spherePosition, 1);
Your cube is not the same size or rotation of the unity cube ?
No it is 5 units
then multiply by 5
but yeah if your middle-of-face is 2.5 units away it would be:
Vector3 knownOffset = Vector3.forward * 2.5f;
Vector3 worldSpaceLocationOfFace = transform.TransformPoint(knownOffset);```
that would be the "front" face
for the top face use Vector3.up, for the right face Vector3.right, and so on
I'm writing a custom saving system with player prefs and trying to make a list of my PlayerPrefsData generic class so that I can access and modify all settings with ease. The problem is with compering the type of PlayerPrefsData witch is a generic class. Is there a way to store all generic classes as field types in a list like this?
public PlayerPrefsData<float> SoundsVolumeSetting = new("SoundsVolumeSetting", 1f);
public List<FieldInfo> AllSettings { get; private set; } = new();
private void DefineAllSettings()
{
foreach (FieldInfo fieldInfo in typeof(SettingsManager).GetFields())
{
if (fieldInfo.GetType() == typeof(PlayerPrefsData<>))
{
AllSettings.Add(fieldInfo);
}
}
}
public void SetSetting<T>(string key, T value) where T : IComparable
{
GetSetting<T>(key).Set(value);
}
And here is the troublesome line:
if (fieldInfo.GetType() == typeof(PlayerPrefsData<>))
Help plz
I'm facing a challenge in my project using Quest 2 and Hand Tracking 2, where manipulated objects pass through others instead of interacting. When trying to move an object towards another, it doesn't stop but goes through. I use Unity and seek guidance to configure realistic collision detection between objects. I appreciate any assistance from the community to enhance this experience.
Best regards,
don't crosspost
okay!
managed to do it like this by adding a parant base class: cs typeof(PlayerPrefsDataBase).IsAssignableFrom(fieldInfo.FieldType)
If you wanna do something more robust (baby steps towards networking/compression/modular save files) google up MessagePack - it's a doozy of a first step to wrap your head around how it works, but then at the end you can convert anything to/from a byte[] and send it over the network, save it to a file, put it in a playerpref string field, etc. Once you get it set up, you just annotate your fields and it does the rest.
Alternatively if you want something more readable/editable/easier to start/, you can serialize to json, stuff that into a single string, and put into player prefs
and even easier, if all your settings have a ToString() and a ctor that can hydrate the object from a string, you could just ToString() everything and store that in a player prefs field
thanks! I did some research on player prefs based systems and couldn't find anything much useful. Now I have something to read
MessagePack is a pretty heavy duty tool for what you're likely looking to do, but it's.. a really useful thing to know how to use so .. if you can get over the learning curve (feel free to @ me - no DMs though) it's pretty useful for nearly anything you want to save/load
JSON seems really decent for saving, but I'm building a game for WebGL and I'm not sure how it runs on it. Will do more research on saving for this platform, but wanted to have an easy to work with solution already
JSON is probably your best step if you're just starting with this sort of tech, since it's easy to debug and edit during dev.. and you can use both at the same time (I do) if you need
MessagePack isn't the only option either, it's just data serialization, you can do it with JSON, BSON, MessagePack, FlatBuffers, whatever.
ProtoBuf too
or even ini files
I have one of those libraries kicking around.. such an ancient format
It doesn't make much difference which one you choose, especially if you don't need to communicate with a different app and is entirely read/write within your own game.
At that point you can literally just slap on Unity's JsonUtility and that will be all.
https://gist.github.com/cdanek/5f92392308f78c91a83a8c6550f51f2e - INI file implementation.. this is pretty old code but it works solidly for me
Your original question doesn't have much to do with data serialization tbh, but you are looking for a way to find all serialized values
I would generally not recommend doing it with reflection like you did.
unpopular opinion: i sorta like INI formatting over JSON
Why is that, what advantages are there?
none!
it just looks nice. :p
JSON is way more functional but .. is also just a bit noisy.. for flat/simple/non-collection data types, I feel like INI files are underrated 😛
(I don't actually use it very often but I did for one project, and it was pretty successful)
the project had an IP address and version number that I wanted to be able to set/read easily without doing builds
That doesn't really matter though, the de/serializer should be opaque to your code.
The only difference is if you are editing it by hand.
which I was for this.. it would just bit a few extra bits of nonsense for a JSON config file
but INI files are probably best left in the 90s 🙂
From a practical standpoint, JSON is supported by practically everything, while INI you either need to bring in a library or slap one together (granted it's very easy to do) but there's also no formal spec for INI, so it's not a feasible long term solution either.
I have a question, will provide more info if needed, but imagine deforming a simple plane by setting the vertex heights to random numbers. I'm trying to do this on a plane mesh I imported from blender, and I'm getting a noticeable tilt into the top right direction in the patterns like so:
something up with the triangles or uvs that could be causing this effect, as i'm not touching them
I'm going to guess it has something with the vertex order in blender being different than in unity and something is off in the loop
Define "tilt" ?
it's got like a terrainish texture on it right now, you can see how all the green stuff streaks from bottom left to top right
and it's like that for every seed, so it doesn't appear truly random
Let's make things clear. Should we be paying attention to the green colored spots? What are they?
Is the issue that they appear in a diagonal pattern?
I assumed the green parts were the brown terrain clipping through a base plane.
Yeah, it's not clear entirely what the issue is and what should we be paying attention to.
@signal pelican please provide some clarification.
It's just a simple terrain shader I threw together, green being lower heights, brown being higher heights, here is the same plane with a default white material
like the folds are all pointing north east
Are you driving the heights from a noise function?
i was and it wasn't working, so i just went back to using one call to random like so: vertices[i].y = UnityEngine.Random.Range(1f, 5f);
and the result is still that
i mean the noise i was using was working but it was also stretching like the purely random one is stretching
the lague noise tutorial works fine, so i'm sure it's just some weird thing with looping through the vertices incorrectly
if you subdivide a plane in blender the center is vertex index of 0
Do the same type of artifacts appear if you try different seed values?
but im still not really sure why vertex order would matter for a completely random assignment
yeah
Are you post-processing the height value at all? E.g. smoothing
none that i can see, in the same scene i have bits of lague's terrain gen working and producing results that id expect
but he makes the mesh on the fly, im using a subdivided plane from blender
Hmm yeah that's weird then. I wouldn't expect those types of artifacts to be showing up given pure random height values. Can you try and just set every 2nd vertex to height 3 and all others to 1 or something? Make sure you get the expected results.
Just to confirm, this isn't just an artifact of the lighting direction is it?
i'm not sure? i can remove the lighting and it still looks liek that
i do recalculate normals call after assigning the random values
you're going to have to post some code I think
here is the side to side comaprison
the one on the right is from lague's tutorial with noise and octaves and all that good stuff and just a quick shader i put on
so same lighting conditions
Maybe your base mesh is being rotated/scaled weirdly before you put height values on it since it's coming in from blender?
Also if it works fine with the procedural mesh why not just use a procedural mesh?
im using dreamtek's forever engine
and i like how it extrudes paths
and it also extrudes meshes
but i havent figured out how to extrude a procedurally generated mesh in forever
so im adding a basic subdivided mesh from blender, the forever engine is bending the plane, and then i deform the plane after with noise
that was the plan anyway lol
You're deforming the plane after it's being bent? Are you accounting for the curved surface in your deformation?
well these current examples are not bent
You wouldn't get the left side image with just random number though. It would be more like white noise.
So there must be something extra you're doing on the plane.
Otherwise you wouldn't get smooth height changes.
ive commented a bunch of stuff out so the only thing on the left example that's going right now is:
for (int i = 0; i < vertices.Length; i++) {
vertices[i].y = UnityEngine.Random.Range(1f, 5f);
}
mesh.vertices = vertices;
mesh.RecalculateNormals();
Ah, maybe it's due to normals recalculation that it looks smooth🤔
I appreciate the look guys, i was maybe thing something obvious wuold jump out but the seb lague one on the right is working so ill figure it out
ill have to redo the brakceys one for like the 5th time i wonder if it happens on his
Without testing it, I think it might just do that if you have such a small or random scale on a mesh that has its triangles set like that
I guess the issue is that you loop all the vertices like that. It probably reveals some kind of pattern
yeah the only thing conceptually that's throwing me off is that the order shouldn't really matter in any way
whether i'm saying the 0th height is 6.3 or the 97th height etc
It matters if the random has biases and you're experiencing them; but it's probably not visually dense enough to see that
Yeah the order won't matter if you're using random heights. It will matter for noise based heights though.
It probably wouldn't if it was "real" random. But pseudorandom might have some patterns under certain conditions.
appreciate the look guys, ill figure it out
Can you show the result with something that's actually got larger gradients, not just what is practically white noise?
I'd also love to see a 2d version(rendered to a texture) of it.
It's very useful to have a 2d setup for testing when working with noise and other type of procedural generation
Just picture a quad that's two triangles, raise any one corner and you're going to experience a gradient on the triangles on the diagonal
but if you're actually raising the sides reasonably to form a gradient over a larger distance then you're not going to see that, because the whole mesh expresses a real shape
not just white noise on geometry
Hi! Is there any way to allow each user to choose if want personalized ads or not?
You're forced to give them a choice on ios via ATT. You hope they don't figure it out on android (via denying access to idfa). Are you actually contemplating giving them that choice? Because it's a weird one if you're trying to monetize at all
Pretty sure google requires you to give them a choice as well for the app to get published.
it's an install-time permission disclosed in the store, you don't have to actively ask like ios... yet
Hmm... Did something change in the last few years? Pretty sure I was forced to implement a popup prompt in an android game I worked on a few years ago.
Maybe it was to be aligned with the iOS port that someone else worked on.🤔
only thing that changed is that you used to not have to declare the ad id permission at all, but google has been steadily increasing privacy requirements for the past couple years. If your popup was functional and actually turned off tracking (and was respected by ad sdks), you spent dev time generating negative value :(
Well, that was a requirement from the client. And it's not their first game on the story, so I don't know. Anyways, it's a matter long forgotten.
How can I do this from unity?
Some kind of native API. Aren't you using some plugin for ads?
What are you using for ads?
Pretty sure I was forced to implement a popup prompt in an android game I worked on a few years ago.
yeah, when gdpr was first introduced iirc. Games need to have popup that confirm if user consent to have their idfa sent or not
when I serialize an instance of a scriptableobject to a json file and then deserialize it in another session, it says the object then cannot be instantiated. Is there a way of storing a scriptable object where I can avoid this?
I will make my github public for a min so people can help me out
at least have the courtesy of linking directly to where your issue is instead of making everyone else try and find your issue
I'm working on it
sorry was a temp link while i got everything made public
CharacterStats is the SO that i need to instantiate from a json
ah there it is. you're serializing references to a ScriptableObject.
https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html
If the object contains fields with references to other Unity objects, those references are serialized by recording the InstanceID for each referenced object. Because the Instance ID acts like a handle to the in-memory object instance, the JSON string can only be deserialized back during the same session of the Unity engine.
I must be missing something obvious as all the other SO's I need to instantiate seem to be fine?
where am I serializing a reference? I'm just trying to clone the stats from a character
I'm not intending to serialize a reference at all
https://github.com/btarg/FModGame/blob/main/Assets/Scripts/ScriptableObjects/Util/DataTypes/CharacterStatsDictionary.cs
your KeyValuePair class contains a reference to the SO
each character has an instantiated Stats so we can have different stats for multiple characters based on the same SO
ofc it does, I want to store all of the SO's values
now go look at the actual json that is produced and look at what it shows for those CharacterStatsKeyValuePair instances
yes because you are serializing an object that has a reference to the SO, which is a UnityEngine.Object
ah... how can I store that dictionary without using a reference then? do I just manually copy all the values into equivalent vars in the CharacterStatsDictionary rather than directly using CharacterStats?
I've been using a lot of non-unity c# classes in my project so forgive me for assuming it should act the wrong way
damnit I should have read this, doing more googling and found a reddit post that basically does exactly that
https://www.reddit.com/r/Unity3D/comments/168piou/how_to_serialize_and_deserialize_scriptable/
you could do that. or you could create a class that holds that data. Then you can create an instance of that class in your SO and just convert all those fields to properties and expose the class's variables through the properties in your SO
oh ffs why did I not think of that
i will try doing exactly that
moved all of the basic stats to "raw character stats", and i'm just pointing these vars to them
or should I be directly accessing them everywhere like rawCharacterStats.
naw, making them properties like that is the way to go. i don't know why you've made them private though
yeah i changed em to public i just noticed that
habit
getting a few errors but the json is looking very promising. annoyed with myself that i didn't think to just extract these properties but its good that its halfway there already
Index accesses itself
public int Index => (Index + 1) % list.Count; this getter is accessing itself
you probably meant to have Index and NextIndex as separate properties?
what do you think happens when you access Index?
you're not overwriting anything, that's only a getter
When using Graphics.DrawMesh() or DrawMeshInstanced(), what strategies are there for raycasting against these meshes? I know drawMesh() doesn't interact with the physics system..
some background:
I'm writing a factory game where belts, etc are all represented in data as NativeArrays/etc so I can use jobs. So DrawMesh would be really practical here. However, the player must be able to interact with factory objects to e.g. add belts, delete machines, etc.
There are approaches to object picking that use shaders and GPU readback, essentially identifying the object that a clicked pixel belongs to.
Here's an example:
https://medium.com/@philippchristoph/pixel-perfect-selection-using-shaders-16070d3094d
What they do here is when the player clicks, they render the whole scene with a special shader that renders each object with a different color, then reading back the color of the pixel under the cursor to identify which object it belongs to.
Rendering the whole scene to read back one pixel is a bit overkill though. You could pretty easily render the scene with a super narrow FOV focusing only on where the mouse is and render it to a 1x1 texture, saving you a lot of GPU time.
wow that's pretty nuts. never thought of that approach.
Any other strategies you can think of? It looks complicated/time consuming to implement. What I thought of:
- spawn gameobjects with colliders in the area the player is focused on (game is on a 3D grid)
- raycast and find which 3D grid points it goes through, then check data on whether those grid points contain objects.
- or maybe just use gameobjects to render instead. Have a system that creates/destroys gameobjects as the data is changed. gameobject has an id that references the data it is rendering.
Oh, if it's in a grid and you don't care about pixel perfect accuracy, just getting the first occupied cell under the mouse, then that sounds like the simplest approach. Just to be clear, the "raycast" would not be Physics.Raycast, but manually stepping through the grid cells along the screen point ray until you find one that is occupied.
Now that I think about it, I need to discern the sides of the grid. If the mouse is on the top side, place object above, etc
The grid traversal isn't necessarily a simple problem, but it has been solved.
For example: https://github.com/cgyurgyik/fast-voxel-traversal-algorithm/blob/master/overview/FastVoxelTraversalOverview.md
It should be possible to deduce which side the ray enters the last cell from.
I think I'm gonna start with just using game objects to render. I've shot my foot more than once in the past not keeping it simple.
As the game design settles, I'll know my requirements and performance bottle necks better. Then it might be worth it going the shader or grid traversal route.
im tryinng to find leaks on my jobs code
and got this leak, that i understand says that at line 241, theres a leak with a float4 array
0x0000017fdc2743cb (Mono JIT Code) Unity.Collections.NativeArray`1<Unity.Mathematics.float4>:Allocate (int,Unity.Collections.Allocator,Unity.Collections.NativeArray`1<Unity.Mathematics.float4>&)
0x0000017fdc2742b3 (Mono JIT Code) Unity.Collections.NativeArray`1<Unity.Mathematics.float4>:.ctor (int,Unity.Collections.Allocator,Unity.Collections.NativeArrayOptions)
0x0000017fdc283203 (Mono JIT Code) sapra.ProceduralGeneration.WorldGeneration.WorldChunkGenerator:ScheduleParallel (sapra.ProceduralGeneration.TerrainConfig,sapra.ProceduralGeneration.GenerationInstance,sapra.ProceduralGeneration.WorldGeneration.PointOfInterestData,sapra.ProceduralGeneration.DisposableArrays,Unity.Jobs.JobHandle) (at F:/Projects/Coding/Personal/TerrainGenerator/Assets/sapra.ProceduralGeneration/Runtime/_WorldGeneration/ScriptableObjects/WorldChunkGenerator.cs:241)
however going to that line, thats not there
//Generate the weight chain
NativeArray<float4> VegetationChained = new NativeArray<float4>(vegLength*vertices.Length, Allocator.TempJob, NativeArrayOptions.ClearMemory);
NativeArray<JobHandle> vegetationWeights = new NativeArray<JobHandle>(VegetationPacksWithID.Count, Allocator.Temp);
for(int i = 0; i < VegetationPacksWithID.Count; i++){
VegetationWithID vegID = VegetationPacksWithID[i];
JobHandle vegetationLayers = CreateVegetationTextures.ScheduleParallel(vertices, vegID.ID, vegID.vegetationSettings,
FinalWeightsChained, VegetationChained, mesh.settings.Resolution, i, finalTextureJob);
vegetationWeights[i] = vegetationLayers;
}
JobHandle WhenWeightsDone = JobHandle.CombineDependencies(vegetationWeights);
vegetationWeights.Dispose();
any idea on what am i missing or could look at?
I can assume that the problem comes from the line above, where there's actually a float4 , but im more concerned on why it doesnt match
well, do you actually dispose VegetationChained somewhere?
I'm guessing the line changed because your code changed at some point
Or maybe it's a bug
Even changing the code, the line number keeps moving targeting the same code
I do, a bit more down the code line, after a job completes. Definetly setting as persistent doesn't throw an error. The job could be expensive so it makes sense. But still, i dont get why isnt it targeting the real line
Hello. I have a problem. When assembling bundles in Addressable, the RAM overflows and the assembly is not assembled. How can this be fixed? In one place I read: "I solved that by creating binary files containing all label data for each tile and added the binary file as TextAsset to the prefab, reducing the file size of all prefabs to 280 MB. So the build process worked again.". But I don't know how to do this. Please, Help me.
That comment is describing a solution where they reduce the complexity of how much they are trying to bundle.
I'm curious how "RAM overflows"
so im coding a rhythm game, and im wondering how i could get the note spawning effect to work?
It's a typical C, C++ problem caused by devs who do not have a clue what they are doing
i'm guessing this means "it ran out of memory and gave up"
no, overflow is trying to access more memory than you allocated
like a bounds violation
right, that's the proper definition, but I'm guessing this was just an OOM problem
since i've never seen someone say "RAM overflow", haha
if I saw "buffer overflow" or "buffer overrun", I'd be much more confident that it was a bounds violation
there is such a thing, or at least there was as a RAM overflow back in the good old days where you reached the end of physical memory and just went back and started writing to the start of memory. This was a very bad thing as that was where the OS was loaded, but I very much doubt if that is the case here
ah, true, especially when you were working with physical memory addresses
and 8bit processors
i implemented a toy operating system in college that used segmented 16-bit addresses, so it wouldn't be that hard to run off the end and come back to zero
Win 3.1 did it all the time on the i386
Can someone tell me what the return type of GetContentForEntry in Unity's Cloud Code is?
https://services.docs.unity.com/content-delivery-client/v1/index.html#tag/Content/operation/GetContentPublicEnv
I'm using it to download a bundle from a private bucket in Unity's CDN and it's returning 4.5MB of data instead of 2.4MB as is the size of the uploaded asset in the bucket...
I'm expecting it to be a byte[] of the entry, but I guess something else is on top of that and I can't figure it out for hours now... documentation is seriously lacking here
Byte stream at first sight: application/octet-stream
There's a content-disposition header which includes info on what is being streamed (file name and extension)
If all else fails, save it to a file, and upload it to a file format recognizer online
Hm, I'll try that, thanks for the help @fresh salmon
good day?
could someone help me
In that state, unfortunately it's not possible. Way too much information is missing
See #854851968446365696 for instructions on how to ask a good question, and make sure to post it in the appropriate channel
Yeah, after a lot of trial and error, for some reason this seems to return a 307 redirect URL to a different URL that contains the actual data... I have no clue why this was implemented in this way though...
At least I know what's happening now, thanks once again
I think they mean just having the note icons visually appear on the screen.
But I have no idea, so you could definitely be right
honestly i have 10% of a clue of what im doing
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
This is the code advanced channel.
Perhaps try in #💻┃code-beginner if that is the case?
Is there a way to quit the standalone application in a way that indicates an error occurred? Or should I just call Application.Quit() in my catch block.
Will that actually stop the application though? Isnt it running in native code?
read it
I did. I’m not sure if it will because the application is not running in c#.
what?
The unity runtime environment is not running in c#. Therefore I am not sure if this will work.
you write your scripts in c# but the engine is in c++
I think you need to learn how Unity, C# and Computers in general actually work
I asked a question and you told me to read it. I explained why i asked that question. I know how c# works, i know how computers “in general” work. I do not know what calling Environment.Exit will do when the whole process is not written in c#, which is why I asked.
do you know what an Application Domain is?
Yup
then what is the problem? Environment.Exit exits an Application domain, the language that that domain is written in is irrelevant
On the documentation you linked it says it returns an exit code to the operating system, not that it exits the application domain. I was unsure of how that would work if the operating system didnt start the process, which i think is a valid question.
that is the same thing which you would know if you knew how anything running under Windows worked
Love the superiority complex attitude i get whenever I ask a question in this server 👍
Don’t need to know every single thing about something to know “anything” about something
you profess knowledge which you obviously do not have
Knowing what an app domain is different knowledge than knowing what returning an exit code to the operating system does when while in a script
And a process can have multiple domains, so even if the domain is exited unity could still be running right?
no it cannot, an Application can only have 1 domain