#archived-code-advanced
1 messages ยท Page 170 of 1
field initializer?
the thing you have
num1?
it's created with the default value for its type, which for an int is 0, and then when start runs it is assigned to 31
never felt like I have to elevate my problem here. I am having issue regarding Texture2DArray not properly showing up in Graphics.Blit. When I call Graphics.Blit(source, rt ); as a single texture2d layer, it works, but for some reason using Texture2DArray in source shows up grey (128/128/128 value). To me, tells me that A) Texture2DArray isn't compiling the texture2D I've append using Graphics.CopyTexture method, or B) Graphics.Blit isn't recognizing it as a layers of Texture2DArray, and showing me 0th layer (or null).
Has anyone came across dealing with Texture2DArray and Graphics.Blit?
The other options I have in mind is that I was just going to use regular Texture2D and load them one by one into texture slots of a custom shader.
I guess I need to ask this question, How can I test Texture2DArray and see if there's any texture stored in it's array?
anyone know in java how u get the whole string when u enter something?
like if i wanted bob john
customer.Name = input.next();```
Hey, in this script https://pastebin.com/mDVks281 I check a box area to determine if a room can fit, but for some reason I can't figure out, the check center is occasionally (important distinction) in the wrong place when the previous room is rotated. Here's a screenshot to help. The green lines are where the center of the box check is and the red line is between the generating node and the center of the box check.
You can see that the hall at the bottom right does a check in the correct position in the room with the lamp, but the other side of the hall placed the check 90 degrees from the desired center. I just have no clue why after hours of fiddling
Is this perhaps what you are looking for? https://www.tutorialspoint.com/java/io/bufferedreader_readline.htm
It's been several years since I've last written in Java... let me play around with it on my end.
yup
This doesn't look like a Unity specific code. Are you asking us to help you with your Java problems now?
My assumption is that they may be trying to write something for Android specifically. That is curious though because I would expect Unity to already have wrappers around text-based user input.
Yes it does. Use normal UGUI.
TextInput on android will literally bring up the keyboard on android devices.
When working with IMGUI, I used to be able to create styles based on built-in editor styles (e.g., var newStyle = new GUIStyle(EditorStyles.helpBox)) and then name my new style, and the new style would have the same background image as the original. This no longer works.
Since (I'm guessing) Unity 2019.1 and the introduction of UI Elements, the GUIStyle.normal.background texture seems to always be null in built-in editor styles. According to this post (https://answers.unity.com/questions/1744845/cant-change-button-guistyle-background.html), it seems like the background image may be provided by some USS file and the built-in style name is used to access it the texture. So when I now copy/clone a built-in style and then change the name of the copy, the background image is no longer used by the new style.
Is there any way I can get access to the Texture objects used by built-in editor styles so that I can manually apply them to my custom GUIStyle instances?
Hey all. Asking this one again as it's causing some problems with renaming and optimizing scripts.
Because of this, when something is renamed, it breaks every reference to the script everywhere in the project
Even when it should be renaming it including in the meta files
I use Rider, and I haven't had any issues renaming MonoBehaviour scripts in the IDE, as it renames the meta file at the same time and Unity recognizes the name change. It's been a while since I used Visual Studio with Unity, but I thought there was a way to enable the parsing of Unity assets even for large projects, but I can't recall details. It was in the Unity extension settings, IIRC.
Without having an IDE correctly handle the renaming of component class files, the recommendation is to rename them inside of the Unity editor so that references do not break.
@austere jewel I watch both video about async/await operations and unitask. But now I still succumb to this incredible performance hit. any idea how I could force the async calls to a different thread?
UniTask is not about threading operations. It's practically an allocation-free task-based replacement for coroutines. If you want Tasks on another thread you need to thread them with Task.Run, or if using UniTask it has methods to transition to another thread, though it's not ideal
Task.Run(() => { //some code
});
I definitely appreciate the reccomendation for Rider, which I have considered. What is particularly strange is that this all worked until recently and I don't know why.
Has your project increased in size recently? Perhaps it passed some threshold which has disabled the handling of Unity metadata?
Sad part is that playing with Unity's texture stuff, this doesn't work in multi-thread ๐ฆ
if youre loading a texture at runtime, your best bet is UnityWebRequest
AssetBundle..
how are you loading your bundle?
LoadAssetAsync<> from a directory first
Using async operation here, which is nice, but still... the performance I'm getting hit hard has to do with the texture manuplation after loading the texture in.
what kind of texture manipulation?
Set Pixel + Apply?
Combine stuff into texture2d array, run through material, call graphics blit, then asyncgpureadback.. finally saving to storage.
tex2Darray using graphics.copytexture function.
I might have to yield in some part of the code...
unity is really not good with dealing with heavy texture manipulation at runtime.
I was about to recommend graphics.blit but looks like you already are.
i dont know any other suggestion for you, sorry about that.
Threading is not an option for this.
You can try some external library maybe to handle your texture manipulation instead of unity which you can thread on your own
I was originally using the job system to literally read pixel by pixel and then saving that to the result.
seems like using the shader is much faster than the job system.
Seems like I've hit unity's bottomneck here.
memory bandwidth is always the bottleneck
I guess the question I have is this, when loading texture from asset bundle, is the texture already instantiated to the gpu memory?
I could save the performance by relying on using pointers instead of handling texture2d around..
Texture is uploaded to gpu only when it needs to be rendered
I've reached to the most optimal code by far and still can't squeeze down that performance block.. Thanks malloc!
maybe optimize the architecture?
Might just get away without encoding to png, and save it as .t2d extension..
is it possible for a local file system package A to reference local filesystem package B ?
right now it does not appear that Unity resolves those packages recursively
okay
now that i figured that out
why aren't assemblies in local package B visible to A when A references B as a dependency correctly?
nevermind
i figured it all out
Is it possible that I could use the UniTask to wait until next frame if the current frame exceeds over certain time intervals?
E.g. if current frame exceeds more than 100ms, await nextframe()
you could run a stopwatch and when it hits a certain threshold then await nextframe
var sw = Stopwatch.StartNew();
foreach (var item in work) {
item.Do();
if (sw.Elapsed > threshold)
{
await UniTask.NextFrame();
sw.Restart();
}
}
but that stuff should actually not be done in tasks but rather in jobs
can't. Most of the stuff needs reference, and can't do it multi-thread due to unity's api texture/gpu calls.
can't is just a lack of willpower ๐
can't, in this case, is a limitation I have from Unity's api.
I can do it, if it was thread-safe.
can't you make it thread safe or is it blocked by the API?
blocked by API.
too bad
Might have to hack around by using Time.time and set that on every child object that's running async operation.
IsObjectMonoBehaviour can only be called from the main thread
any help is appreciated
is there a way to completely remove Input so that i can see everywhere in code where it is used?
ctrl+f or h?
that'll let you find where it's used
you can't just remove the existence of a class as far as i know
Just use find references. If you're not using it already to find things, get on that immediately!
even smarter lol
i meant in order to prevent another developer
from usin git
so that when they pull this project and write new code
it will show as a compile error
is it because you want to use the new input system?
You cannot do that sadly.
Sounds like you want to build a .dll library
only you can build the .dll and cannot be modify by other developers?
It would be nice if the legacy input system was a module that you could just remove
but sadly it doesn't seem to be listed as a module
public static class ClassNuker()
{
[InitializeOnLoad]
private static Fire()
{
NukeClass(typeof(Input));
}
public static NukeClass(Type target)
{
// ???
}
}
how 2 complete???
that's what i thought
it's okay it took me just a few minutes to port over
i really wish old Input would die
where is class CSharpCodeDegenerator???
i don't understand how people can be doing this for years, in 2022, and still use Input.touches and Input.GetMouse... with switching for mobile and all this bullshit
that's for aspnetcore...
even the unity docs say Mouse.current instead of Pointer.current
Why are you poking around asp.net stuff when you should be looking into .NET for unity? @cedar ledge
sorry it was a bad joke and i wasnt paying attention
still looking for help with this btw
really wish there's a way I could break code down based on current frame time since the beginning of frame.
Oh and Time.time did not help.
You can use DateTime.Now.Ticks
You should prefer UtcNow, not Now
Now is an expensive property
DateTime.Now can also throw an exception if your system has broken time settings
I ran some performance benchmarks, and it seems that iterating over a dictionary with its keys is more performant than iterating over a list... why would this be?
what's the Task equivalent of creating a new thread and starting it without waiting to it to finish?
just fire and forget
Task.Run
I get a warning saying that I'm not awaiting it
Also, I thought that was for CPU-bound methods. I'm doing an infinite loop of listening to a network socket
Task t = Task.Run(...);
``` the warning will go away if you assign it to a variable
So if I don't intend to use that, just use _ = ?
so Task.Run isn't just for cpu-bound methods, then?
So the thing is
In Unity
I don't think the threadpool it gives you is a real background threadpool
Like it would be in normal .NET
I think it might actually run your code on the main thread anyway
I'm converting a whole bunch of thread code to task code so I'm learning
But in general, it doesn't matter what kind of code it is - Task.Run is fire and forget. The returned Task object is what lets you not forget if you want to not forget
should I configureawait(false) on that?
its a real threadpool if you do Task.Run(Foo), but mainthread if you do async void Start() { await Foo(); }
The thread pool exists in Unity just as it does in real .NET
It's the same implementation
ConfigureAwait(false) is only necessary if the thread that the continuation runs on is important
// we're on the main thread here
await SomeAsyncMethod(); // this might run on a background thread
// this code is back on the main thread
// we're on the main thread here
await SomeAsyncMethod().ConfigureAwait(false); // this might run on a background thread
// we might be on a background thread here
So ConfigureAwait(false) should not be used if you call Unity API methods after the await
Does anyone know anyway to get a random palette from something like coloors.co using an api?
You would need to see if Coolors provides an API itself
Does Coolors do anything special to generate a palette that couldn't just be done manually?
Should be pretty simple to generate 256 random colors
There's even this https://docs.unity3d.com/ScriptReference/Random.ColorHSV.html
Teach me senpais, how to make scriptable object which can save a list of items. The hook is that depending on scriptable object options, the list could hold either int or string or bool or what ever. I searched for hours now, tried generic classes approach and etc. To level where I am thinking to make just 4 scriptable object scripts for different types. But I really want to learn how to make it in correct way....
string scriptbatbleObjectType = "string";
struct MyStruct {
string name;
TypeThatCanBeString,IntOrBool data;
}
List <MyStruct> = new List<MyStruct>();
I am looking to convert a list to "layers" so i can place objects on top of a perlin noise map.
How would i go about this?
Layer1 would be tileset.Add(0, prefab_plains);
Layer2 would go on top of that, like a tree or random object but me not smart
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.
Is brotli compression not working for anybody else? For WebGL builds? MacOS 12.0 (Monterey)
I don't get my build with the .br extension
struct MyStruct<T> {
string name;
T ThisCanBeBoolIntFloatObjectEtc;
}
But with this I cannot Make list if I do not Decribe T beforahand
A couple nasty solutions:
- use an
objectfield - Use multiple fields and an enum field to tell you which one is populated
you could use dynamic as well, if it can change during runtime
and use reflection to find the type
Dynamic is pretty much not useful in Unity, as IL2CPP doesn't support it
true
Also probably slower than the enum method ๐
yeah, it will do runtime checks constantly instead of during compile time
Well just created Custom variable with all possible strings. and will just show correct GUI depending on type with UI toolkit....
Has anyone done parallax UI on a procamera 2d before? I can't render button UI by using the camera of the layer I'm interested in.
also it seems editor does cannot use [System.Serializable] with this, so in editor even if initiated correctly, you cannot see values.
yeah, though you could write a custom inspector for it
Yea, but in the end I would need to write multiple Editors for each type. Sio it kinda destroys Idea of unifying it ๐ฆ
you could simply show a string of the value, everything should have a ToString method iirc
atleast, if you don't need to change the values in the inspector
Which version of Unity are you using? Support for generic serialization was added in 2020.1
2021.2.9 My editor refuses to agree with that statment ๐ at least in list ๐ it shows same way as if list would be from Objects
It works differently, you have to use SerializeReference and probably make a custom propertydrawer for them
public class BoolButtonSciptableObject : ScriptableObject
{
[SerializeField] public List<CustomButtonClass<bool>> m_ButtonsList;
}
[System.Serializable]
public class CustomButtonClass<T>
{
string title;
T value;
}
Hi
hey everybody! How is it possible to get a type mismatch with FindObjectOfType...?
what do you mean type mismatch?
well um, couldn't be clearer, when my fields are hydrated by my findObjectOfType, there is "type mismatch" written inside them
and i did some debugging, but my objects are indeed the ones i want them to be, but...
here's my whole script
(ignore my intern monologue in comments)
and when i click "hydrate":
I have an event OnNetworkTick that needs to be invoked repeatedly. Currently, I'm using another method StartNetworkTick to handle the infinite loop. The problem I'm having right now is that it doesn't stop when I exit playmode. I think it also should run on the main thread due to unity limitations. How can I fix this? Is there a better way to set up an asynchronous infinite loop?
// ServerStart():
// Task.Run uses a threadpool, not main thread
_ = Task.Run(() => StartNetworkTick());
// event
public delegate void NetworkTickEvent();
public static event NetworkTickEvent? OnNetworkTickEvent;
// loop
private async Task StartNetworkTick()
{
while(true)
{
OnNetworkTickEvent?.Invoke();
// accessing singleton might need to be done on main thread?
await Task.Delay(NetworkCore.Instance.NetworkSettings.TickDelay);
}
}
i need to add a getComponent, that's it?
ok i'm dumb, thanks everybody bye lol
I have a player in resources folder how can I get it value with script instead of using inspector
Thanks
ok nvm update: still having types missmatchs,
But when i try to debug.log values within the scripts themselves, well... it works like a charm.
I'm going to be using it like that, but i'm worried this might blow up on me at some point
an asset can't reference gameobjects in the scene
if those managers are prefabs you need to set them to have a reference to the prefab assets
not an instance of those prefabs in the scene
ok so i'm trying to use dark magic basically?
that's a shame
Honestly i'm not trying to overuse this. Basically, i have a list of scenarios, and i'll be using this to add scenarios with a simple button, instead of a click and drag.
(my tool is aiming towards non-devs)
are the managers prefabs?
nope
why not?
I have a player how can I give value of player to var with just script and without inspector
well you could go ahead and do that and have your button load the prefabs instead
No it's advanced but what I mean is that I want the value of the instantiated player which is over the photon network
so i would destroy the object already existing, and spawn a new prefab, and keep the current instance of the prefab in a reference in my asset?
what do you want? A reference of the player?
you're not asking a good question
be precise :)
Ok let me explain just a min
So let make it clear what issue I have is that I want my camera to follow the player which is over the network i just want to give a value with script i dont want it to be done with inspector
what value?!
the position of the player?
what do you mean the player is "over the network"? the gameobject exists locally and is synced over the network
i can't help you if you don't be precise with your question
you might want to try on the Photon Network discord server / forums for this question, maybe.
Ok so any so just tell me that how do I get the camera follow the player without drag and drop
so you want to find the player gameobject from a script? FindObjectOfType<Player>()? This is a really beginner question. Maybe move to #๐ปโcode-beginner
Ok but the player is in resources folder but thanks
why didnt you bother mentioning that?
like, at all?
var player = Resources.Load<Player>("Prefabs/MyPlayerPrefab");
Thanks but that is not working for me
feel free to elaborate on that
alrighty then
But where are you from
i live in your walls
If you go to the middle of the Indian Ocean and dig really deep, you might pop out somewhere nearby me
Ok i am on my way to your home ๐
malloc about to drop a thesis of a question
its better to use System.Threading.Thread for an infinitely running worker thread, because Task.Run is meant to be for short tasks and you're basically starving your thread pool this way.
bool canQuit;
void OnApplicationQuit()
{
canQuit = true;
}
new System.Threading.Thread(() =>
{
while(!canQuit)
{
//do some work here
}
}).Start();
Just landing
ok thank you!
Anyone knows in async operations (UniTask in my case)
when cancellation token get called, does it discard everything that goes after Yield in method?
private async UniTaskVoid FlipAsync(float duration, CancellationToken cancellationToken)
{
var endTime = Time.time + duration;
float angle = transform.rotation.eulerAngles.z;
float counter = 0f;
bool didAnimation = true;
while (Time.time < endTime)
{
counter += Time.deltaTime / duration;
float step = (counter < 0.5f) ? counter : Mathf.SmoothStep(0.5f, 1f, counter);
if (didAnimation && counter > 0.80f)
{
animator.Play("PostFlip");
didAnimation = false;
}
transform.rotation = Quaternion.Euler(0, 0, Mathf.Lerp(angle, VelocityRotation.eulerAngles.z - Mathf.Lerp(0f, 360f, counter), step));
await UniTask.Yield(cancellationToken);
}
shouldRotate = true;
}
Here code I have and I experience troubles that this little piece of shouldRotate = true is not getting executed if token is cancelled
Well yeah, the method never gets continued
So that yield is the last line that executes
is there a way to ensure callback?
it's just async operation tied into unity ecosystem
hi guys.
Can unity take several image files and put them together for me into a spritesheet or tileset? I seem to have trouble getting my assets into the project as single images, all the tutorials are using tilesets
i'll load up my project again and give that a shot
well it said it packs it but it doesnt show a preview
preview is in scalable window. You need to expand to actually see preview.
Even if it's empty it'll be just empty texture.
ohh man i feel dumb as hell. so it's minimized you have to click drag from the bottom up to see the preview. lol
Hi! anyone know why i need to recompile my code to get this executed? i was hoping it launches when i launched my project, but it's not
InitializeOnLoadAttribute allows you to initialize an Editor class when Unity loads and when your scripts are recompiled.
Maybe you have domain reload disabled. It would only run in actual reload and a recompile triggers that. If you want to run it with reload disabled you need the enter play mode attribute
here? Just activated it
That should make it run (based on what the docs say)
but it says "enter playmode"...
i'm talking about when i open my project
do i really have to screencast this to explain it? ๐ญ
no I get it
no i understand it
thank you ๐ญ
nope! it's not
Static constructors with this attribute are called when scripts in the project are recompiled (also known as a Domain Reload).
Heโs already doing that
okok i'll try some things, but really it's weird
yeah
wait a second, do static constructors load after each domain reload?
Without attributes
or only on play?
what if you do [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]?
domain reloaded resets and restarts everything
those attributes will not run if their underlying trigger does not fire
trying
still not working :/
but if i may
I have automatic domain reload unactive, cuz i prefer reloading manually
BUT
When i launch my project, i "can't" reload manually, cuz there's no changes made in my domain. So hitting ctrl+r doesn't even execute the methods if nothing has changed.
sort of a general C# question ... i thought i was being clever by making a class that contains an array of delegates that it runs in sequence according to instructions as an alternative to a certain type of unity coroutine i was using a lot, and it does work great except the stack trace in the debug log messages is near useless because it's showing only the container class internal methods instead of what the delegates are actually set to - there's probably nothing i can do to fix that, right?
like that's just how delegates work, i figure
tried setting the stack trace log type to full but it's the same thing, not that kind of problem
Why use an array of delegates when you can use a normal delegate?
Action d = Function1;
d += Function2;
d(); // calls Function1, then Function2
oh it's meant to run in update, like calling the container's update invokes its "current delegate" which return an instruction whether to repeat itself or to move to the next one, like a sort of very simple linear state machine i guess
yeah, though not exactly success but just "is done doing whatever it does"
Func<bool> d = Function1;
d += Function2;
foreach (Func<bool> m in d.GetInvocationList())
{
if (!m())
break;
}
you can actually do that with delegates like this
though a custom implementation can be optimized better to avoid the array allocation
would that solve my issue though, i mean my own solution is already functional but the problem was that the stack trace is useless for debug purposes since it all points to the container
yeah i guessed as much, was just wondering since i like how simple it's to use and would like to keep it, but that makes it a little sketchy in the long term
It seems like something that might be worth asking in the C# Discord
Plenty of .NET team members hang out there, so if you're lucky one of them might know a way to solve this and chime in
hm yeah thanks
Is there anybody that has experience with Unity's Gaming Services? Particularly with Cloud Code.
I've replicated the Starter pack purchase from the demo into a test project and got it all to work. I want to implement a system where players can buy characters in my game, but only being able to do so once. Therefore I'm trying to make the code reusable by using a parameter, to input the itemID that I want to purchase instead of hard-coding it. But my JS skills are lacking. I'm not sure how to implement it.
I've tried replacing:
const purchaseResult = await purchasesApi.makeVirtualPurchase(projectId, playerId, { id: "STARTERPACKVIRTUALPURCHASE" });
with the following:
const purchaseResult = await purchasesApi.makeVirtualPurchase(projectId, playerId, { id: Starterpack });
The Starterpack is a variable I added to the script.
However I'm getting an error:
------------------------------
ReferenceError: Starterpack is not defined
at module.exports (PurchaseStarterpack.js:33:127)```
If anybody is able to assist me feel free to @ me. I'll be around doing more digging in the docs
The Starterpack is a variable I added to the script.
I don't see it anywhere in the script
My apologies, lemme paste the entire script
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.
still not there
I don't understand
I don't know what that system is, but it's unlikely that it injects the parameters as global variables. Have you checked the params parameter?
I haven't TBH. I'm not seeing much documentation or examples to use the parameters of Cloud Code. I'll do some more digging to get a better understanding. I'm way over my head here.
That actually worked ๐คฆโโ๏ธ.
I declared const StarterpackParameter = params.Starterpack and that worked thank you
help with tasks plz:
i have a scenario :
var returnVal1 = MyTask1Call();
var returnVal2 = MyTask2Call();
// I want to await task1 AND task2 here
var returnVal3 = MyTask3Call();
i do know how to await them with Task.WaitAll(myTaskList) but i dont know how to do it when they return values
Hey there! is there an attribute or something so that a method of mine gets called when my project gets loaded, but waits that my scene is loaded?
oh wait, would that work...?
damn
trying rn
thanks!
(cuz it's not in runtime)
you talking on edit time?
yeah
ahhh
might still work though
yeah, is worth a try
an indirect approach if the above fails
https://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
ExecuteInEditMode isn't really a solution for that
you can call WaitAll for the task objects, and get the return value using Task.Result
ExecuteInEditMode awake?
That would require having the component in every single scene
seems like something which would work, but needs an extra gameobject to be in the scene
yes
That'd suck
hmmm i will try that
thats why i said indirect (:
I'd just do InitializeOnLoadMethod + sceneLoaded
idk if sceneLoaded works in edit mode thats why i already said "if the above fails"
I'm not sure sceneLoaded would even be necessary actually
There's EditorSceneManager
Which probably works
Would need to be tested though
my "component" is a static class lol
(and the above failed)
as suggested by zombie, look into EditorSceneManager APIs if there's any event for scene load
it should work in edit mode, but limited to only editor if that satisfies your need
it does, yes :)
hmmmm
You can do something like
static class EditorSceneCallbacks
{
[InitializeOnLoadMethod]
static void Initialize()
{
EditorSceneManager.sceneOpened += SceneOpened;
}
static void SceneOpened(Scene scene, OpenSceneMode mode)
{
EditorSceneManager.sceneOpened -= SceneOpened;
// Do stuff
}
}
I haven't tested it, but it might work
I'm assuming you just want to run some code once when the editor first opens, but after it finishes loading the most recent scene
when a task finishes without exception, you can use Task.Result itself
EXACTLY
but i've done exactly this, and doesn't work
not available directly
i can do.. taskList[1].AsTask().Result; though
is it bettter than using the getAwaiter?
umm sorry i dont have knowledge of UniTask.
Task.Result is only available Task<T>
GetAwaiter().GetResult() should also work in your case
Have you tried just doing the code inside the InitializeOnLoadMethod?
The scene might be loaded when that runs
public class Startup {
[InitializeOnLoadMethod()]
static void StartupMethod() {
CharacterCreationMenuItem.CreateCharacterEnum();
CharacterCreationMenuItem.CreateChoiceEnum();
if (ScriptableControllersInEditor.instance != null) {
SceneManager.sceneLoaded += ScriptableControllersInEditor.Hydrate;
} else {
ScriptableControllersInEditor.instance = AssetDatabase.LoadAssetAtPath<ScriptableControllersInEditor>("Assets/SCOLTool/Debug/Controllers.asset");
StartupMethod();
}
//Debug.Log("Up and running! Tool ready to be used.");
}
}```
here's my method
Is this a scriptableobject?
that's what I meant yeah
which is a built in method for achieving this
stuff like the package manager preferences etc use this
oh
To have scriptable objects acting like singletons?
yeah
and i thought i invented something new lol
You'd do
[FilePath("Assets/SCOLTool/Debug/Controllers.asset", FilePathAttribute.Location.ProjectFolder)]
public class ScriptableControllersInEditor : ScriptableSingleton<ScriptableControllersInEditor>
{
// ...
}
thanks so much, i think i'll use this unity thingy from now on lol
Then you can access it via ScriptableControllersInEditor.instance
Note that you need to call the Save method in order to write changes to disk
So if you have a custom editor etc you need to do ScriptableControllersInEditor.instance.Save(saveAsText: true)
Any ideas why uploading a 1MB Array to a computer buffer (type structured) will result in compute buffer being initialized to 0 instead of uploaded array values
show code
I am working on an advanced inventory system. Because there are like tons of items there will be spelling mistakes for strings for sure. Is it possible to let the code editor Suggest a string when doing items.add("")? Like it does request "stick" for example
Or when I input some sort of ID instead it previews the Associated item name
Use an enum instead of a string perhaps?
Could you explain how that would work or give a reference?
guys can I bake 2d lighting in unity?
I think I'm having performance issues because of them
This is a simple introduction to enums https://www.w3schools.com/cs/cs_enums.php
Could anybody direct me to a tutorial on creating a gaussian blur against a heightmap or 2d normalised float array?
its actually just this https://en.wikipedia.org/wiki/Kernel_(image_processing), pretty simple but computationally expensive, whether your data is normalized doesn't matter to the filter
I guess the slowness comes from calculating the 3x3 neighbours of every pixel
I can at least can started with this info, thanks for the pointer!
Hi. I'm making a space game where I have two scenes, one is the location where the player is when he is in su-light speed (fighting for example) the other is the system in hyperspace mode. The player can freely jump between sub-light and hyperspace.
The thing is when the player is in sub-light scene I want the system to continue running in the background (so the ships that are traveling in hyperspace continue traveling)
An example of this working is Elite Dangerous
Is there any simple way to do this?
You can load a scene additively.
But then my ship will collide with hyperspace objects right?
If you need only certain gameobjects to keep running then you can mark them as DontDestroyOnLoad and they won't be destroyed when the new scene loads.
I'm not familiar with Elite, but could you not just keep track of how much time passes and feed that into your Hyperspace scene when you re-load it? That way you'd only need to do a single set of calculations to get the new positions instead of keeping it all ticking away in the background
hmm good tip ๐ค
the only problem is that a use case is a ship that's in pursuit that might enter the space the player is in after a while
the more I think about this I should just create a simulation that runs in the background (without gameobjects)
Not if you use multi scene physics
Just implemented a basic version of this now, exactly the output I wanted. Thanks so much for the link!
How can I extract error message from AsyncGPUReadback?
what editor is this that adds item:
Has anyone had issue with AsyncGPUReadback.RequestIntoNativeArray<T>()?
had to rework around 80 percent of my code, but i got it. thank you very much!!
i think its vsscode
thanks!
Architecture problem that's coming up for me often. Thoughts solicited.
I have a game configuration object (persisted to the database, CRUD'd in admin tools) that gets sent to a client. Example: Level and Taps Per Level (how many taps in the client are required to upgrade to the next level). This object is mostly static (not static, but rather unchanging).
I have a client model, with things like "level" and "current taps".
Where should logic go that checks to see if a tap upgrades the level? Should it go in the configuration object, taking a client model as a parameter, in the client, taking a configuration object as a parameter, or in a helper class of some sort that joins the two, perhaps with a static method that takes both objects as parameters?
a hypothetical LevelUp object should subscribe to tap events in some way and the subscribed handler has the logic.
LevelUp being a configuration object?
being a "manager" type thing in the runtime
The subscription to the event is a bit harder, since I'm on a client/server architecture, so I have to duplicate/validate/sanitize this on the server
K.. I can do a manager object in the client, but .. the server would have to duplicate it.
only needed on the server i guess... the taps are sent to it right?
They actually are.. complicated, but taps aren't really 100% "taps" in the client, they can be auto generated by auto-tappers
Yeah.. I mean, technically yes but the downside to that is it would require a round trip to level up, and it's not particularly cheat-sensitive
If the player sees 5..4..3..2..1 taps to upgrade and then there's a delay, that feels odd
well, its the same principle either way
I could do a static game logic class in the shared library and just call it on both the client and server
what you essentially want to avoid is that a tap triggers a roundtrip through all game systems, instead have the tap do what it does locally and fire off events from it, that way only stuff that needs to run, does run and your logic is decoupled
mm hmm.. good point
It's a little bit more complex because I'm not actually sending the updates to the server every tap (obviously), just sending them periodically every 30-60sec (or more, maybe every 5-10 minutes).. but I think that approach is the right one
POCO player object that increments taps; static method on the player object that takes a configuration object as a parameter (and can calculate tap-derived data), and the configuration object itself is a POCO
maybe you need some client side prediction and reconciliation with eventual consistency
for some things, yes, but for this i'll just trust the client
tap tap tap and they have agency over what level they are - but I can validate the update sent to the server
perhaps even count "human taps" and see if it's absurdly large given the time since the last update
you can send a lot of ints over the network per second ๐
i mean, true, but this is also a BigDecimal of my own creation (it's still small, in terms of byte[] size when it's serialized for network traffic), but I'm also hoping to have the server capable of supporting thousands of concurrent players
especially if its not a broadcast
my model is a bit lazy at the moment - the entire player object is serialized and sent to the server on updates
okay, thats different then
it's not huge, but.. you know, it's reasonably big
later on i'll denormalize it and just send something like "taps since last update" or whatever
but for now..
[MessagePackObject]
public class ClientSendPlayerModel
{
[Key(0)] public PlayerModel PlayerModel { get; set; }
}
๐
(that's my network message to the server)
and playermodel has....... some stuff in it
๐
Ugh, problem. So.. Player Model was going to have an action OnPlayerWarpLevelUp, but I realized that I'm actually periodically sending updates to the client from the server (which the client takes as biblical, so it throws out its local copy). This is going to make unsubbing and resubbing to the events problematic.
Any obvious solutions? I could probably:
- Pick through the incoming object model, compare it against the local model and update the fields one by one (a really huge nasty piece of work, and probably fragile if I add new items to the object model)
- Create another event to signal a new POCO has come in, and to unsub from the old POCO and sub to the new POCO
- Create some (stupid) method like
bool CheckForAndDoLevelUp()on the POCO, which sucks because it requires the user of the POCO to bothAddTap()and thenif (CheckForAndDoLevelUp()) { ... animate the level up, update the UI with the new level, etc ... }
hey! so i want to make a generic selection ui that can be used at different places in the code. It's built with a list of options and the player picks one of the options and then it returns the value, after the click.
what would be the best wait to do that? i was thinking of maybe using async but i thought there might be a common unity way people go about solving this?
maybe just use a callback?
Yeah use a callback function
that'd be the standard way
or return a Task if you want to get all Microsoft-y about it.
then the caller could choose to use a callback, or to poll for the response, or whatever
Hey yall, asked this before but didnt get any reply hoping someone has some thoughts here. Im using an isometric tile map (z as y).
My q is rather simple, take the mouse position and figure out which tile is being selected. Im using right now Camera.screenToWorld to get the mouse position into a world position and then grid.WorldToCell() to get the cell position.. this works fine but only for the ground level, it doesnt seem to care about the tiles on top. I thought this being an isometric tilemap that it would just work but curious to see if anyone has any ideas?
@sly grove yeah thought a bit more about it and was also starting to lean towards callback, alright, thanks! ๐
A bit of a long shot, but GetCurve(FbxAnimLayer pAnimLayer, string pChannel, bool pCreate) - would, pChannel be something like "FBXSDK_CURVENODE_COMPONENT_X"? Docs aren't clarifying the API difference to the C++ variant (https://docs.unity3d.com/Packages/com.autodesk.fbx@4.1/api/Autodesk.Fbx.FbxProperty.html)
It looks like FBXSDK_CURVENODE_COMPONENT_X translates to just "X" according to
https://help.autodesk.com/view/FBX/2020/ENU/?guid=FBX_Developer_Help_cpp_ref_fbxanimcurvenode_8h_html
'FbxTime' does not contain a definition for 'SetSecondDouble' - well that's going to be a challenge... ๐
If I wanted all the tiles in a row, I'd probably just use LinQ to select the matching tiles by their ID. I imagine each tile and object carry the tileID they are over.
They should have their height, and their tileID. So should be quick to select and sort through
Assuming I understand the goal mind you
Hello, im trying to calculate a position offset
the position offset offsets the camera position when added
the goal is to calculate the offset requires to be at a certain position
the values I have to try calculate this is
- My Quaternion rotation
- My Position
- Target Position
I need to calculate the offset based on my quaternion rotation, what is the best way to go about this?
specifically i think you want subtraction
@regal olive @dawn zinc it's the best editor in the world. Rider
Hello! Not sure if this is advanced but is there a way to use a generic function with types defined in code run without using reflection?
I saw there is a way to do it with reflection but for me it sounds like overkill
I want to do something like this
what you want to do exactly?
public static void RemoveKeyIfNoEntries<T,Z>(Dictionary<T,List<Z>> dictionary, T key)
{
if (!dictionary.ContainsKey(key)) return;
if (dictionary[key].Count == 0)
dictionary.Remove(key);
}```
MyCoolFunction<typeof(blah)>(arguments)
here you have an example off a generic function
i remove the key of a generic dictionary if the list of Z is empty
You cannot do that specifically without reflection
If you don't know the type at compile time, it cannot be passed as a generic argument without reflection
I see... thats sad xD
That's why many APIs offer MyCoolFunction(Type type) and MyCoolFunction<T> is just a wrapper
You mean MyCoolFunction<blah.GetType()>(arguments)? typeof is used when you know the type at compile time, which in that case you could just use it in the generic call.
Yeah i guess i will have to do an overload with (Type type) no?
Do you have more context for the example?
why cant he do MyCoolFunction<T>(T argument) ?
I dont know T at compile time
Ok I have a list of types that all of them inherit from the same
So you control the types in question?
Could you write a small code sample that is more accurate to that?
Just trying to get an idea of what you want overall
It sounds like you could just use virtuals or an interface
The thing with virtual is that i dont have instances of the elementd
So i wanted to have virtual static
But that doesnt exist
XD
Well not virtual statics, but you can have them in interfaces now
virtuals are coming later
If you have a Type and you want to create an instance, you can do Activator.CreateInstance(type) to create a new instance using the default constructor
And yeah
public interface ISomeInterface
{
abstract static void SomeMethod();
}
// ...
public static void CallSomeMethod<T>()
where T : ISomeInterface
{
T.SomeMethod();
}
Oh thats amazing
But yeah, you can't do this in Unity yet since they don't have support for it
I want exactly that xD
Since it's a .NET 6 thing
You can sort of simulate it though I suppose with empty structs
public interface ISomeInterface
{
void SomeMethod();
}
public static void CallSomeMethod<T>()
where T : struct, ISomeInterface
{
default(T).SomeMethod();
}
then you do
public struct SomeStruct : ISomeInterface
{
public void SomeMethod()
{
}
}
But yeah it's not an ideal workaround
Hmmm
Let me put the example more elaborate
public class Info
{
public Base type:
public Func<bool> condition;
public Func<object, BaseData> generateBaseData;
}
public List<Info> InfoList;
public IEnumerator StartAndWaitForAction(object injectData)
{
foreach (var info in InfoList) {
if (info.condition()) {
InstantiateMyThing(info.type, info.generateBaseData(injectData);
yield return WaitUntilFinished()
}
}
}
I guess the instantiate my thing
Before was done with generics
I just need to do an overload with type
Aaaand that works?
What would InstantiateMyThing do?
Instantiate a monobehaviour of type type with the injected object
That shouldn't need anything special since there are already non-generic overloads of methods like Instantiate, AddComponent, etc
I see...
Ok cool thanks then i was just confused with our actual methods
Didnt realize i can just use addcomponent with type
I should note that you probably should use UnityEngine.Object instead of object
Since those are different types
Instead of generic
The latter is actually System.Object
It depends, but it's probably fine if it's intentional here
I just wish i could have done it with the virtual static, would have been much more elegant
Lets wait for .net 6 then :p
Thanks so much!
someone knows why while building some scripts by some stupid shit dont have references? in most stuff its just asmdef files using post processing but while build its just gone idk why
maybe someone knows if its way to strip assets on headless build? aka i have audio files/textures which i dont want to have any size just dummy file
server build does this
in in 2021 and later at least
i don't remember if it's in 2020 LTS
we using Headless Builder asset on 2019 unity and now we using 2021, its any chance its not needed anymore?
based on the docs for server build, it omits a lot of stuff
that would make sense only in game play
it shoudl be clear headless builds can definitely render
it's up to you to not render
but i believe teh Server Build option does what you want
is anyone aware of a good v-ray conversion library? especially for maya? it seems so cantankerous to bring pre-existing assets from e..g Turbosquid into Unity because they all use VRay materials
or maybe some kind of pro importer for 3dsmax or maya that can correctly interpret or at least easily allow manual override of materials?
Anyone coding using DOTS + ECS? Are there any good resources for getting started with the current package?
I'm worried older tutorials circa 2018/2019 might have lots of outdated information or use outdated base classes and such
it's not really ready to be used
what are you trying to do
you're trying ot do X.MyMethod() where MyMethod is a static "virtual" void MyMethod(this T xValue) { ... } ?
i see there's a lot of confusion about what you watn to do lol
I'm trying to adjust the opacity of a tilemap dynamically. This is my tilemap (FadeScript currently doesn't do anything useful):
How do I access the right parameters to adjust the opacity? I'm assuming something like tilemap = GetComponent<Tilemap>(); would be a good start, followed by <something>.renderer.material.color = new Color(1, 1, 1, 0);, but I'm having trouble accessing the tilemap
Ok, got it. There's another import from using UnityEngine.TileMaps
Yes that would have been my first option, but i went with a different one in which i had to use a not so elegant way which involved either using generics on runtime with unknown type and no reflection or a different way. I just sent the type and used instancing with the type instead of the generic variation of that method. Should be ok now. Thanks!
Why wont this pause the game?
It wont even enable the menu
ok did some debugging apparently the gamestate isnt changing
How the hell am I supposed to implement one of the most important mechanics, pausing
did you check if p menu is running?
it is
Learn how to pause your game in Unity in less than 2 minutes without setting timescale using events.
This allows you to still use time-based logic in pause menus and background systems and can even be extended to work for cutscenes, loading screens and game over screens.
TIMESTAMPS
00:00 Intro
00:05 Game State Manager
00:51 Hook up Player Move...
was trying to follow this
but IDK who to trust anymore
ok
ahh this is hard to do without sound
can you post your code
or more bits of it
Sorry I gotta do something
hmm comments seem to think he is wrong
yeah maybe
but brackey's tutorial tricked me
and im told not to use Time.timescale
Who the fuck do I trust?
nvm i think i have some time
sorry if i came across as rude
im just confused
no its fine
i also just had to do somthing
you might as well use the event system now that you have it but maby just for having the menu tabs open
yeah i deleted all the shit from that tutorial
That's normal, there are a bunch of ways to handle this, so you get a lot of different opinionated answers.
It will also get more complex when you start wanting to store and retrieve states :)
The comments advocating for Time.timeScale are wrong
But I haven't watched the tutorial video, so maybe the implementation it shows is also bad
Using unscaled time like some of the comments suggest isn't a real solution, it's just a bandaid on top of a hack
okay i found a solution
{
return;
}```
putting this in events i dont want to occur while the game is paused
along with timescale
That's an approach that will work better yeah, though why do it with timeScale?
so things wont move
There are ways that are nicer to use that don't require you to add code to every pausable component, but I'm a bit busy with some work atm so I don't want to get too distracted writing up samples lol
no its not part of every use of
{
return;
}```
the timescale is part of the pause script
Right, I meant that there are ways you can do it that don't need if (PauseMenu.Paused) return;
unless you want the PauseMenu to disable all scripts that should be paused , not realy
Help how can you instantiate prefabs from a dedicated prefabs folder? (c#)
Resources.load or addressables
i have this code:
foreach (var x in blockdata)
{
if (HasEnoughItems(Items.Item.Stone_Pickaxe, 1) && x.ItemType == Items.Type.Stone_Block)
{
foreach (var pick in blockdatacopy)
{
if (pick.Item == Items.Item.Stone_Pickaxe)
{
foreach (var block in blockdatacopy)
{
if (block.ItemType == Items.Type.Stone_Block)
x.BreakTime = block.BreakTime * (float)pick.BreakMultiplicator;
}
}
}
}
}
Item.Item holds every Item there is in a game, is enum
blockdata holds all data an Item holds, is List<class>
blockdatacopy is just a blockdata to get access to default variables, is List<class>
item.Type holds every Type an item can be, is enum
pick as in foreach grabs the blockdata defaults for stonepick
block as in foreach grabs the blockdata defaults for every item that is some sot of stone
this is all in Update, but the last if statement gets looped somehow (the values are getting smaller each time)
but how could that be? if the copy isnt altered (it doesnt) how could the values get smaller every time (i checked, block.BreakTime gets changed)
these shouldn't be the same, right?
it should, because i have to get the pickaxes data default values and the blocks data default values
well that's too much looping for me to follow right now, but it sounds like what you think is a copy is not a copy?
How does one go about making a server authoritative shooting for projectile based bullets
my only guess is that instances of class stored in different lists named blockdata and blockdatacopy might be the same
is savesystem and storing data advanced?
I probably know the answer to this but I just want to shoot my question here, is there a way for unity ui to render outside the game scene just like how the docking version of dear imgui?
its a very complicated topic. i wanted to avoid typing a long passage first, you can read some good papers on it.
for this to work, the server authoritative movement should be working and setup properly.
for shooting basically, the client needs to know the current server tick, this way when the client sends back the data, the server will know the exact moment the shoot happened (with some +/- in delay which you need to compensate)
when you shoot, send the same tick back to server
i) for raycast based, the server needs to rewind time, check raycast, apply damage if raycast is successful, and restore back the time
ii) for projectile based, the server needs to rewind time, shoot the projectile and then restore back the time
Is it possible in Unity to get the color of a pixel from a screen? (Not the program, the screen) Basically what a color picker does, but not just internally
Basically, I need to get the color of a pixel anywhere on screen, even if it's not inside the unity window
Only via OS APIs
for me the unity color picker does work outside the unity ui
I'm currently using an AutoHotKey hack to /kind of/ do this, problem is it's horribly inefficient and requires autohotkey to be installed on the computer. As well as it most likely triggering anticheat
presumably they mean runtime
No, no, in the program
Autohotkey scripts can be compiled as well
oh dang, yeah hmm
Oh? I'll look into that
would it be crazy to like...take a screenshot and sample the pixel?
I need to be doing this more more than 10 times a second
Hello folks, I need some help figuring out how to rotate a multi part camera model I have so that the lens ends up looking at a defined point.
I need to rotate the two axis shown only, but I can't wrap my head around the math, any pointers would be nice ๐
AutoHotKey can manage it without going over 0% CPU usage
I would use the animation rigging package http://docs.unity3d.com/Packages/com.unity.animation.rigging@latest/
Thanks, will give it a shot
I am a little unsure as to whether it would be able to handle your setup so I might take a look at some of the samples and see whether they apply to the scenario
i feel like i saw something about them using it for robot arm animations that seemed like they would be basically that
this would be weird, because the list is being filled in awake, an after the fill is being copied
so how are you copying it?
using new keyword for classes for copying?
Wuh oh..
I have no idea how to avoid this exception
The autohotkey script & unity program run independently, so unless I can somehow perfectly sync them this will always happen eventually
create logic to lock files and wait until the lock is properly acquired
That error also happens when you don't properly dispose of the file handle when you're done using it. Make sure you're using a using statement to do disposable ops:
using (FileStream fs = new()) {
// Use stream here
}
// stream is disposed here
I am closing the streamreader at the end, i'm like 90% sure its the AHK script conflicting with unity
Alright, but make sure you're using that using statement pattern, that closes the stream even if an exception gets thrown into the nested block.
It basically compiles into a try-finally block
i did what you said and wrapped everything in a try statement and commented out of all of the errors, if I can't see them they aren't there :) @fresh salmon
this is probably the hackiest thing i've ever made
๐ค
nvm I think this was AHK's fault
yep, for some reason it outputs BRG instead of RGB by default
why on unity 2021.2 while building with usage subtarget Server its taking script definitions from subtarget player? its any way possible to force buildpipeline to use x definitions
seems like i cant set server as targetgroup in buildplayer
by some dumb reason on linux build in same stuff its using il2cpp soo wtf
You can make the camera render to a texture and then look at pixels in the texture.
Not the program, the screen
No
Not as far as I know anyway
You want to make something like a color picker?
..uh, something like that yes
the current method I have for getting the screen pixels is.. flimsy.
as in it causes hundreds of errors per second that I just have to try catch and ignore
also I've been awake for like 18 hours now so my code is getting progressively worse
To be clear you want to sample pixels outside of the program right?
I think you'd have to use specific code for each OS you need to support
this is for me, so just windows
It's definitely possible, Photoshop does it
In that case there may be something in .NET you can use
Loop
{
FileDelete, %A_Temp%/sample.RGB
; 0,0
PixelGetColor, color, 950, 500, RGB
FileAppend, %color%`n, %A_Temp%/sample.RGB
; 0,1
PixelGetColor, color, 950, 510, RGB
FileAppend, %color%`n,%A_Temp%/sample.RGB
; 1,0
PixelGetColor, color, 960, 500, RGB
FileAppend, %color%`n, %A_Temp%/sample.RGB
; 1,1
PixelGetColor, color, 960, 510, RGB
FileAppend, %color%, %A_Temp%/sample.RGB
Sleep, 100
}
```(holy fuck discord has ahk syntax?)
this is my *current* method getting screen pixels in autohotkey
I literally log their RGB values to a file and then read the file
(I take 4 samples to average together)
Maybe you could look at this? https://www.codeproject.com/Articles/17335/Pure-C-NET-Desktop-Color-Picker-With-Magnifying-Gl
(i just googled that so no idea if it's useful)
I have never actually used windows API directly through unity, I understand that there are some parts missing. But I think it should be at least theoretically possible to use any windows API from Unity?
my goal is to mimic the lightsync "screen sampler" effect from g hub
I think you can import DLLs to do stuff
here's an old example: https://forum.unity.com/threads/windows-api-calls.127719/
you can probably find something more recent
Literally a decade old hahah
But it's also likely that it hasn't changed much
oh god 2012 was 10 years ago
10 years ago, I was still using Unity & Unreal full-time :D. Those windows api calls haven't changed iirc. Although pricing was vastly different back then
That said, there are smarter systems for DLL support now, so although that old way is perfectly fine and usable, there might actually be some smarter approaches if you really want to dig into it
maybe use the default build pipeline and set up the player settings asset the way you need
don't punish yourself over unity's flakey support for build automation
When deserializing transform values, is the order relevant? I'm restoring a game state by serializing the local scale, local rotation and local position of some objects. when I deserialize this, is there a specific order in which to apply the new values? Scale -> Rotation -> Position?
I'm getting some weird deserialization issues and I'm trying to track them down.
it shouldn't matter, no
Saw a mod for Gorilla Tag that allows for custom maps. It exports UnityPackages but with the extension changed to .gtmap
I know it's a UnityPackage because if you try to open it as a UnityPackage in Unity it works
You put the .gtmap in the folder and when you boot the game up it appears in the level selection screen. How can I use UnityPackages for custom levels?
(Extra proof that they're UnityPackages and not AssetBundles is that they save scripts and you can use them)
I assume they're loading them in at runtime or something but I'm not exactly sure
And does it contain normal Unity scenes that are loaded?
Yeah
I think so Idk
You make your level and I believe it takes the scene and everything in it
And then turns it into a UnityPackage
(Unity)
Do you separate interfaces/abstract classes from the implementations using different assemblies?
If yes, can you suggest me good naming convention for that?
For example CompanyName.ModuleName.Core for abstraction modules and CompanyName.ModuleName.Implementation for implementations?
Have never done that no
I'd probably do something like modulename.api and modulename.impl
anyone know how I could achieve flat shading programatically?
I have made a mesh in a script but if I recalculateNormals() then it does smooth shading
For my VR input SDK abstraction layer I use CompanyName.Input for the interfaces and CompanyName.Input.Oculus, CompanyName.Input.SteamVR, etc...
You have to duplicate the vertices. One duplicate vertex per face that the vertex is part of
and do the normals manually
RecalculateNormals will interpolate them and give you smooth shading (though not sure what it does when you've properly duplicated the vertices)
Maybe?
probably not
the normals for such a shader would have to come from the geometry
and without duplicated vertices, the normals will not be right
maybe for some limited set of simple primitive shapes
Why not just do it the typical way, by duplicating the vertices?
@summer summit i am seeing online that split vertices is the best way to achieve hard edges
opensubdiv supports creases but that's really complicated for your use case
for game purposes you can look at how Cities Skylines does it
otherwise i don't think you should separate it this way in C#. if you want to do friend use [assembly: InternalsVisibleTo("OtherAssembly")] in your AssemblyInfo.cs
this way you can declare internal classes
and when you create a new assembly that needs to access them, e.g. one that's part of your broader library, put in that InternalsVisibleTo attribute
Late response but yes, you can access any native API through P/Invokes by using the DllImport attribute
Anything that exports functions via the C ABI can be called
@valid flame
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class PInvoke
{
[DllImport("user32", ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32", ExactSpelling = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32", ExactSpelling = true)]
public static extern uint GetPixel(IntPtr hdc, int x, int y);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte GetRValue(uint rgb) => (byte)((ushort)rgb & 0xFF);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte GetGValue(uint rgb) => (byte)((ushort)(rgb >> 8) & 0xFF);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte GetBValue(uint rgb) => (byte)((ushort)(rgb >> 16) & 0xFF);
}
var wnd = PInvoke.GetDesktopWindow();
var hdc = PInvoke.GetDC(wnd);
var pix = PInvoke.GetPixel(hdc, x, y);
// Use GetRValue, GetGValue, GetBValue
Note that in multi-monitor setups, this will only work for the main monitor
Hi. Has anyone profiled allocations of local functions that capture local variables but are never converted to a delegate? The MS docs on this say that the compiler can take advantage of the fact that they don't escape the local scope to optimize the closure allocation, but it does not say it is required to do so.
You can look at SharpLab to see what the compiler outputs
C#/VB/F# compiler playground.
Look at the IL it generates
Be sure to select release mode
I know, but Unity uses il2cpp and mono and a custom older compiler, how can I be sure it's going to be the same there?
Those are irrelevant because this is a C# compiler optimization, not a runtime one
Unity still compiles the C# with Roslyn to get IL
ok thanks
C#/VB/F# compiler playground.
The closure becomes a struct here, so it won't allocate garbage
yeah thank you
Of course, you'll need to tweak it to match the code you have
But in the general case it should be fine
Hi
hi
Suppose I am taking the photon instantiated value in the gamobject called target so the gameobject target will only get value when something or player instantiated and so but while starting they are showing error such as give value in inspector how to solve this issue
https://www.toptal.com/developers/hastebin/iriyojekay.coffeescript
I am trying to load my audioclip from my streamingAssets folder due to the project being webgl.
However i seem to be met with this issue.
anyone seen it before or knows a fix. audio files are .WAV
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Can you log the path you're passing to GetAudioClip? Maybe you aren't passing a valid path
Ideally you should use UriBuilder instead of concatenating strings manually because that's an error-prone nightmare
C:/Users/lange/Documents/ProjectVZ/Assets/StreamingAssets\HeroProducts\Smart.wav
this is the path
And how are you constructing the path?
StreamingAssetPath = Path.Combine(Application.streamingAssetsPath, SubFolder, SoundAssetName);```
Subfolder = HeroProducts
Hmm
my files were .mp3 at first but found those are not really supported and that .wav was better
var builder = new UriBuilder
{
Scheme = Uri.UriSchemeFile,
Host = string.Empty,
Path = StreamingAssetPath
};
You can then use builder.Uri.ToString() to construct a path, btw
And yeah, mp3 is a proprietary format so it's not available everywhere
I'd recommend avoiding it at all costs
wav should work, so that error seems strange if the path is correct
Your path does appear to be correct based on this though, so it's strange...
Maybe the WAV contains samples in a format that WebGL doesn't support?
Though I'm doubtful of that
Suppose I am taking the photon instantiated value in the gamobject called target so the gameobject target will only get value when something or player instantiated and so but while starting they are showing error such as give value in inspector how to solve this issue
Photon as in the multiplayer library?
You might want to ask in #archived-networking
it could be. i just renamed the extension. ill go check that out aswell.
Oh, is the file still an MP3?
Just renaming the extension doesn't do anything
You need to actually convert the file to a WAV properly, they're completely different file formats
You could use Audacity or even just ffmpeg to do that
Bro have you created any game
If you use ffmpeg, the command would be: ffmpeg -i source.mp3 destination.wav
Just note that this means converting from a lossy format to a lossless format
alright well i got audacity installed so ill use that
Not created entirely on my own, but I've worked on a bunch of games sure
I work at New Blood Interactive, so basically any game published there I've worked on to some extent
Oh
I'm a support programmer, so I've done programming work on Dusk, Ultrakill, etc
So do you study or do job
I work there
Hi guys, im facing a problem with Photon Networking, can some one help me out? I need to destroy a scene object that is owned by the master client, apparently i couln't find a solution yet.
#archived-networking is probably a better place to ask Photon questions
@random lava do you know
thank you i havent found the networking group sorry
How to make camera follow the player which is instantiated
yes i do
So can you help me with this
sure text me private
Ok
@final steeple converting it normally to wav doesnt seem to have fixed the issue
Could you DM me the file?
I'll try converting it on my end and sending it back to you to make sure
@random lava i can't send message because it is not working
send me a friend request
dunno, why ask a non-code question in a code channel? ๐ค
theres no editor channel. i but i wanted to post in code genral
Are you referring to code for the unity editor?
no
Then you're referring more to level design?
a tad late to the party, but i'm back from the weekend:
Do i need to have a createAssetMenu attribute too? To be able to create the instance? or is it going to create itself?
I might do something really different though, i'm complicating my own task
It'll handle creation itself
CreateAssetMenu is only for if you want to create it yourself in the asset browser, which you shouldn't do for ScriptableSingleton
i'll do something else, way simpler lol
Instead of having my scenarioList inside of my manager in the scene and doing ScriptableSingletonWithMyManagers.Instance.ScenarioManager.ScenarioList.Add(scenario), i'll transform my scenario<List> into a scriptable object containing a list, which i can have as an asset in my project, yadda yadda yadda, way simpler lol
thanks so much though! didn't know about this
np
Wasn't for me, but thanks anyway.
yeah I gave a proper response shortly after, just wanted to give confirmation
I seem to be getting this error whenever i try to grab a file from my localhost (this is a build). the build is on a NAS server HTTPS.
I know i am entering the wrong values but i dont know which ones are the right ones. so if any1 can help. that would be appreciated
https://www.toptal.com/developers/hastebin/lozeqavafe.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
ln 37 - 63
There's nothing wrong with using UriBuilder, but yes, the wrong scheme is specified there
You should use UriSchemeHttp
var uri = $"http://localhost:8080/StreamingAssets/{SoundAssetName}.ogg";
try just doing this
you're putting in streaming asset path
i think there are a lot of things going on and it's confusing you
i'm just guessing where your sound file is
it's impossible to know though
jup.
does it also work with https?
you know what i mean? you're obscuring a lot of places you are probably making mistakes
does what also work with https?
the same scheme
i think the right way to do this is
var baseUrl = "http://localhost:8080/StreamingAssets";
var soundAssetFilePath = $"{SoundAssetName}.wav"; // or whatever!!
var uri = $"{baseUrl}/{soundAssetFilePath }";
does this make sense @normal cedar ?
i mean i don't know what the variables are
but you can set in your editor "http://localhost:8080/StreamingAssets" when you're testing
and then the real path when you deploy it
yeah it does make sense
that notwithstanding, you're going to screw up things like CORS...
have you ever deployed a WebGL game before?
no first time
have you been able to successfully play a webgl you built yourself in a browser?
yeah.
#include "UnityCG.cginc"
#pragma multi_compile_instancing
struct appdata
{
UNITY_VERTEX_INPUT_INSTANCE_ID
uint vertID : SV_VertexID;
};
struct v2g
{
float4 vertex : SV_POSITION;
};
v2g vert (appdata v)
{
UNITY_SETUP_INSTANCE_ID(v);
UNITY_GET_INSTANCE_ID(v);
uint instID = unity_InstanceID;
//uint instID = 1;
uint vertID = v.vertID;
}
any idea why unity_InstanceID would be undeclared identifier?
Ask in #archived-shaders, as here it's more for C# code
Are ECS principals workable in Unity without the ECS package? Would they have any benefit? What would it look like?
in principle you can use DOD and by extension an ECS wherever/whenever you like. Unity ECS is just one implementation of the idea. The benefits depend on what you are using it for. The architecture alone can be of great benefit even when used with GameObjects to make things more reusable/easier-to-change/simpler. You should be able to get the most out of your custom ECS when using it for non-rendered, non-gameobject based code where you can also reap the performance benefits.
Thanks, I thought that might be the case. I think performance benefits would only come into play if you "jobified" some aspects, using native arrays, but I'm not sure how much performance there is to be gained with just modifying transform positions and stuff in jobs. So it sounds like a naive ECS would be more beneficial from a code simplicity standpoint.
DOD has potential to improve performance by multiple orders of magnitude (compared to standard OOP) so long as everything stays optimally data oriented. When transitioning into regular OOP patterns, performance suffers quickly. DOD and jobs complement each other but the benefits are also there on single threads (otherwise parallel compute wouldnโt be quick either)
Interesting -- I will have to do more tests. I'm pretty new to DOD so still trying to figure out how I would write systems that would show any performance uplift for traditional game loop stuff (modifying transform positions, rotations, state booleans, for many players). Seems you want to be passing small structs with few blittable parameters like float2s and iterating over those using jobs? But like you said, even if done on the main thread, if the data was aligned optimally for the CPU there should be performance uplift.
YOURE TELLING ME ITS BUILT IN? HRJSHFJD
The interop is built-in yeah, but it makes calls to external DLLs that must be on your system
If you build for anything else than Windows it won't work
But yeah, it's a powerful way to interact with the system
Pretty much, yeah
I have my own system for calling internal engine functions this way too
So I can get notifications for when a GameObject is created or when a component is added
duplicating verts has performance issues
seems like it must be doable with a shader but I don't know much about them
You sure? Have you tested/profiled it and found an issue?
Sounds like you're trying to prematurely optimize things
Shaders can have performance issues too
hmm maybe but I wanted to put a shader on here anyway
Maybe you should be in #archived-shaders
sure
Oh the dlls must be on your system? Do they come with Windows or do I need them to install with the program?
On Windows by default
damn, thought it might've been the cause of the bug I have
When I try to share the project with other people, their screen seems to not get sampled at all even though the screen sampling service is running
The DLLs used in the snippet I posted earlier come with Windows
Do those people have multiple monitors?
It only reads from the main one
Know that you can debug this, the DllImport attribute can have a property named SetLastError set to true, which pushes an eventual external error onto somewhere, where you can retrieve it with yet another external call to GetLastError()
That's not what SetLastError is for
SetLastError caches the Win32 GetLastError value, it only applies to functions that actually use that system
The functions in that snippet don't use it
They do, but so do I
I already asked them if ANY of their monitors were black while it was running and they all said no
Then make sure they're picking colors on the main monitor
Specifically, it does this caching because the runtime can override the last error value in some scenarios, so it's not "safe" to call the Win32 GetLastError function directly
You can retrieve it via Marshal.GetLastWin32Error()
But anyway, if the DLLs were somehow missing, it would throw DllNotFoundException
gotcha
But if user32.dll was missing, Windows wouldn't even run
i know one of them is on windows 11
but anyway with that code you gave me i should be able to remove the dependency on the seperate screen sampling service
which will make it 1000% more reliable
It should be more performant too because you're not going through disk IO
and much much much faster
I could only reliably sample the screen every fifth of a second before
Yeah you can reasonably do it every frame now
also I can get a lot more samples now
Just cache the IntPtr you get from GetDC (DC means Device Context), I'm not sure of the performance characteristics of that function
I'm still working on that other store project rn, but I'll get back on that screen sampling project later now
I'm removing the dependency on visual scripting since its just bad
I simply just need to clamp the player camera X rotation to not flip around when the mouse moves, and this is the best method I have found - and it doesn't really work. Camera still flips when i reach the top and mouse moves the opposite way to go down too fast. (I am not good with quaternion math- and exposing camRotation.x did not help in the least, as making modifications just caused a ton of odd camera movements)
Vector3 camRotation = cam.transform.rotation.eulerAngles;
camRotation.x -= look.y * lookSensitivity * Time.fixedDeltaTime;
camRotation.x = ClampCameraX(camRotation.x);
cam.transform.rotation = Quaternion.Euler(camRotation);//Move camera up/down
private float ClampCameraX(float angle) {
if (angle >= 270) {
return angle - 360;
}
if (angle > 90) {
return 90;
} else if (angle < -90) {
return -90;
} else {
return angle;
}
}
I would like to introduce you to Mathf.Clamp
Replace all of that with
Mathf.Clamp cannot be used with quaternion -> Euler angles, the math breaks
Mathf.Clamp(angle, -90, 90)
First argument is the float to clamp
second is the minimum value it can go to
third is the highest value it can go to
For me it works
Hold on
You should track your own values that you modify, clamp, and re-apply as a rotation
you should not try to get rotation from an object and clamp that
unless you have a very specific range of motion and rotation modifications that can happen it's just not gonna work
That is definitely one method i was considering, but sounds kind of excessive considering the variables exist already in another โformโ
I had an old project i had it working with, clamping vertical rotation perfectly between 90 and -90 on the euler X axis - but i lost that project :/
It's not excessive, the rotation does not exist in another appropriate form
it only exists as an orientation without knowledge of any rotation about axes
Thatโs what Euler does, but clamped in i believe 0-360
Unity does not store euler angles (outside of the inspector)
the euler angles are entirely derived from the quaternion, which doesn't have any knowledge of x y z rotations about axes
Euler is the converter between the two, giving me back out the active angle and not one that by some poor mistake could be off
and properly setting back with Quaternionion.Euler(vector3)
itโs messing with camera - so the least amount of jitty possible is best (which will happen if somehow camera becomes desynced from store variables), so best to modify the active angles
it nearly worked with MathF.Clamp(), but when it reached around the middle, it would instantly flip down to 90
Thank the heavens a friend had a copy of the source. Found the original function I had used, and now it works like a charm (Similar to what I had shown before, but better scripted to support quaternion math in euler).
BTW, on the side, am I experiencing a bug/glitch or is this just how Unity works? If I set a RaycastHit object's parent, if I do any GetComponent calls on the hit, it performs the search based on either the parent most GameObject or the script containing the GameObject that called the hit.Transform.SetParent (Hard to tell, since both fit my current situation). This is not a problem for me as all I have to do is perform SetParent last, but I was curious it this was an issue or if that is just how Unity works.
In this example, if Collider.enabled = false was called after SetParent, the GameObject running this script would have its collider disabled instead
if (hit.transform.GetComponent<SceneItem>() != null) {//Pickup if interactable is SceneObject
hit.transform.GetComponent<Collider>().enabled = false;
hit.transform.position = Vector3.zero;
hit.transform.SetParent(hand.transform, false);
}
Hello
Is there a way to do this without writing basically the same code twice? Is there a way I could reuse the code?
https://paste.ofcode.org/3biT9cUKTvUBd75PWzfYeAT
No, in C# you have to overload for each number of args you want to support. There are no variadic generics.
@maiden turtle thanks!
I have another problem with generics.
I have these 4 files : https://paste.ofcode.org/simBb9bGCNUYijS5ML8768
If I add an IntGameEventListener script to my object, the selector window for Event is empty. I can however drag and drop an IntGameEvent instance to the Event field (and it actually won't allow me to drag something else there). Is there a way to make my events show in the selector window?
Or a different way of writing this code for that to happen?
Those fields need non generic signatures. There are few exceptions to this in unity, all of them have invariant type parameters.
I wonder why it works when I drag and drop though but not when I try to use the window...
Other than copy pasting the code for all of the types of events and event listeners, is there a way to make this work? I know that if I have a field explicitly for IntGameEvent then those events will show up in the window. Is there to rewrite as little of the code as possible between the different classes but somehow specify the type of Event explicitly?
You can write a code generator, but otherwise thatโs what you have to do.
I added an abstract GetEvent Method to my base class and then overridden it in my IntGameEventListener and added an explicit field of IntGameEvent to that class which I return in the overridden method. This is the best solution I've found for now.
You can implement the non-generic GameEvent and then implement GameEvent<T> on top of it, but really this is just something you have to deal with in C#
Even the BCL has to deal with this, examples being stuff like Task and Task<T>
Or the existence of Action vs Func
You can use my code generator too. It's plugin based, so it's going to be less work than writing one from scratch
There's also C# source generators, though Unity doesn't support incremental ones yet
Incremental ones are much more efficient, so hopefully that changes soon
(and its a bit messy from the build side of things)