#archived-code-general
1 messages Β· Page 374 of 1
yeah the levels are just to tell what its coming. So yeah, i'd keep the scriptable objects
most studios build custom tools to sync their data in an office-local model that everyone can access and back up to with infinite undos (like source control, sometimes it even is just source control)... They use custom tools to automate packaging everything and custom tools for initializing and serializing levels that are compatible with AAA practices for the purpose of compression and optimized load speed for target devices and for mass distribution....
In the end if you're just indie whatever you use doesn't matter :D if it works for you
just an indie working on my first "big expectative" mobile game
i wouldnt give my code to anyone.. because its ugly af
ty again!
How performance intensive you think Collider2D.GetClosestPoint is?
What sort of answer are you expecting?
Thinking about the math behind it, Circle should be the lightest to calculate, then Capsule, then Box and then Polygon
Is there a way, to get a type and let a class accept is as so?
System.Type type = currentClass.GetType();
Singleton<type>.Instance.SendMessage(currentMethod);
Is giving me currently 'type is a variable but used as a Type'
actually it's 3D, we live in a 3D world so it's easier for the brain to conceptualize
For a new coder is 3d easier?
Ja
yes but it's reflection so it's not pretty, something like ((MonoBehaviour)type.GetProperty("Instance").GetValue(null)).SendMessage(currentMethod)
Physics2D.IgnoreCollision();
This uses like "Colliders" but, can i ignore the collision of a group of things? like:
if(enemyHit){
//disable the collisions between you and ALL the enemies, not only the one who hurt you
}
i was trying to access to this but it seems like i cant
also nothing stops you from just grouping them in a list then iterate through them
This does not work, because my script is as object is identified as Monoscript and not what it actually is
can you call MonoScript.GetClass()?
I could in editor, but I need like the dynamic equivalent at runtime.
MonoScript.Getclass itself is part of UnityEditor, so cant use that to call the methods from the runtim Instances
which part are you trying to do at runtime then?
none of the MonoScript stuff will work in a build
The whole monoscript class is editor only
So I am passing in the asset to the editor script, which holds the method string to call for. What I now need is the string to the actual class type, so I can once at runtime get the instance and call the methods from there
Is it possible to set custom mesh renderer bounds? The docs say that the field MeshRenderer.bounds cannot be overwritten, at least in 2019.3
so like Type.GetType?
In the end, I had this more or less hardcoded
Singleton<XRAdminManager>.Instance.SendMessage(currentMethod);
And I want this method to get the dynamic XRAdminManager from the object I stored when assigning the monoscript in editor
Its just personal preference of dynamic code. If its not working at all, I just use a simple switch case
you have to set them in local space, localBounds
Looks like it doesn't exist in this Unity version
oh dang π
i see
thx
That's for 6000, I'm on 2019.3
I cannot change versions since this is for a Kerbal Space Program mod
Ohh, 19, sorry, missed that part
Kind of. In the end, I want to find the instance of a class in runtime which I somehow stored in editor at least the class or whatever I can find via runtime.
iirc if you store the full name of a type from the editor reference (https://learn.microsoft.com/en-us/dotnet/api/system.type.assemblyqualifiedname?view=net-8.0#system-type-assemblyqualifiedname) you should be able to fetch it at runtime with GetType
Hm, will look into this how to actually convert it back at runtime. Thanks π
take a look at Activator.CreateInstance, wont work on Unity Objects though
with empty scene, untracked memory is very less, when i am importing assets, then after using those in scenes, creating those untracked memory even if i unload? what can be the solution then?
If the assets are still stored somewhere or being used inside a prefab or something, they might be kept in memory until nothing else form the addressable bundle is being used
The problem I have , I got the Instances running of different managers. I just want to access them comparing the script file I attached to the runtime Instance
I mean, if there is a better way to get instances of a class at runtime dynamically, I am totally open minded.
not loaded anywhere, where the asset( i mean mesh) was being used, i am unloading that particular scene, even after calling UnloadUnusedAsset, the untracked memory grows? have you encountered this while using addressables?
Only when assets are not being released because of other assets being used from the same bundle. Are you sure, your scene is not creating some garbage, that is not being released?
trying to change ambient enviro. lighting but it is stuck on blue please help :) https://streamable.com/oa2cdp
I disagree... I think you'd have an easier time with simple 2D games first. It's a lot easier to abstract and the math is far more simple in 2D
it's easier for our brain to conceptualize 2D world than 3D math imo
I will start with 2d tmr cause today I spent to much Time
- click the box and select the colour manually.
- #archived-lighting channel
- do you have an editor script that is modifying it?
I wanna make a pixelated game in 2d but I suck at drawing any Tips or websites to draw?
I would say you need to evaluate what you want to do and come to an understanding of how long it's going to take :) For this goal I would recommend:
- fundamentals in illustration, lighting, both traditional and digital (take some courses)
- learn the math involved in pixel art!
- follow lots of tutorials on creating art in general
- learn Unity fundamentals (through the tutorials I linked earlier)
basically I would say in order to actually take on the project of making a game, you pretty much need the knowledge and experience to do it intuitively.
If you want a more simple, easy route check out rpg-maker. Also might wanna move this discussion to a more general channel.
- doesn't work still
- thanks
- shoot maybe tysm
2d and 3d have about the same learning curve, you just have to !learn how to do anything first
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Alr thx
What is the best way to learn how to code? I know people are probably going to say documentation, but so what, do people just look up loads of documentation, and then string up their code with documented code hoping it'll work?
like combining code documentation?
The best way to learn how to code is to start with something you want to do or make, then research the skills you need as you need them
bump
There are myriad tutorials for anything you may want to do
But how? Let's say for example I wanted to make a player with actual physics and it adds a down force so you can jump, what would you research for that?
I don't want to really do tutorials, I want to come up with my own code, plus tutorials don't teach you much beyond doing it how they do
unless you're willing to take classes and learn directly from someone else helping you, tutorials are the only other real way of doing it
I can't imagine anyone saying documentation is a way to learn to code. That's like saying you can learn a language from the dictionary
you aren't going to learn code by brute force or by putting your head into the documentation
You start with tutorials, then modify them to suit your needs
Documentation is reference material, not learning material
oh no? I thought it was as simple as taking Mathf.Deg2Rad in the documentation, looking up what is does, and adding that into your code
Yes if you already know the principles of coding
even me, who's been doing this for years, still uses tutorials for things I don't know. Though I spend much less time iwth them
You can and should do this
But that won't teach you those principles, like what a function is and how to call it
for like 99% of what you want to do, you google "this in unity" and parse the results until you get what you're looking for
But I don't understand, tutorials are limited, let's say you find a tutorial for a basic character controller, but your game needs something more, how do you figure out how to expand it programming wise?
if you want to do everything from scratch with no help AND you don't know how to code, GL I guess ? There's a huge resource for !learn ing how to use unity
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
it's less of a "figure out" thing and more of a "use logic and reasoning to get there" thing
then you start to refine your research
You asked about learning to code, which is a very different question from making a game or a specific mechanic
figure out why the character controller you got from the tutorial does or doesn't work, then change it
But looking at examples is a starting point and yes you would combine this with reference material to come up with a solution
So basically just throw anything at the wall until it works?
No...
no
Sorry guys, I have a learning disability so its hard for me to understand
Anybody out there using VSCode (with Gemini)? any tips for prompt engineering?
Basically just using your brain and thinking how to go about achieving what you would want to do based on your existing knowledge of how the engine works and research into available tools and libraries
A learning disability certainly adds challenge
Tutorials etc build up your base knowledge of what's possible and how
And may provide inspiration or a starting point for code and scene setup
So let's say I wanted to add physics. I know that Vector3.up means down, so I would do m_SomeVector = Vector3.MoveTowards(m_SomeVector, Vector3.up, m_Gravity * Time.deltaTime);
when you say... 'add physics' what do you mean? do you just want things to respond to gravity?
Does your object have a rigidbody on it?
I use character controllers
Vector3.up certainly doesn't mean down lol
okay so what is it?
It's up
Oh so I would do -Vector3.up
Vector3.down
that doesn't really answer the question, can you check what components your character object has for me? Posting it would help
Or yes that
That probably explains why my player doesn't jump
Because I had it go up not down
This code is mixing up direction vectors and position vectors most likely. It's hard to tell because it's unclear what the input and output vectors are supposed to be semantically
I'm curious why you thought up meant down
I don't really know π€¦ββοΈ
I think you need to slow down a little and think about what your code means. You might be rushing and not understanding.
Yeah. here's the thing
So there's this game called Bendy and the Ink Machine, I talked to the programmer on that, and he even held a press conference at a location I forgot, but he said he learned to code by googling "how to do this in unity" the only thing I don't know was how he expanded it for the sequel
The next step is to actually do that thing in Unity, see what went wrong, and remember that for future use
@leaden ice Vector3.up has to mean down because when I negate it, the player goes up
Depending on what you're using, the player itself might be upside down
Make sure its local Y axis (green) points up
Some methods will convert your vector to local space before applying it, like transform.Translate
nvm it was an issue with another float value I was using
No probably some other number you're multiplying is negative
those who used addressables, did you ever face untracked memory growth while using scene load and unload? i am trying to figure out what could be the reason, can't see any light at all. i am thinking is it any device specific problem? i don't have any other other device except my pc right now, not even a mobile. can anyone help me to get my sample test project shared to see if you too are getting the untracked memory? this could give me relief whatever the result comes. sorry to bring such topic here
I can give it a go after work. Upload it somewhere and share the link.
i really don't know how to thank you for this
i will share the file link soon
My guess it's just part of unity implementation and there's nothing you can do about it.
here is the link:
https://we.tl/t-KX88HOg4Ai
83 files sent via WeTransfer, the simplest way to send your files around the world
yeah that might be true, but look at my screenshot from memory profiler window, first one is before scene load, second one after scene load, last one after unload. even after unloading memory only goes down 3mb, then where is the benefit of using addressables to unload things to free up memory. I think i am wrong with my project somewhere, I am really grateful that you agreed to help me. please look into it a bit.
Is that profiling a build?
yeah
Did you try loading/unloading multiple times? Does it keep on increasing by ~50mb every time?
If not, it could just be unity reserving the memory and reusing it afterwards.
it's range is very inconsistent, sometimes after loading and unloading for about 5-6 times, the untracked memory grows to 100mb
sometimes more again sometimes less
Well, I'll have a look when I get back, but don't get your hopes up. I can only use the same tools that you do, so it's unlikely I'll figure out something new.
Might be a good idea to post on the forums. Perhaps some unity staff would see it.
i posted the problem about 7 days ago, no answer till now
that would be much for me for now...then i gotta find someone who have used addressables broadly, i don't know how to find someone, but still i have to
Possible memory leak with addressables?
i spent 2 hours yesterda trying to code a working movements script in 2d en 3d and it didnt workπ
2 hours is nothing. When you are just starting to learn it can literally take days to make something that works, There is a great deal to learn
you are so harsh with telling the truth! π
Better they face the truth early so they can really evaluate if game dev is for them or not
Totally agree, was just jokin. Its good to get the scale of what is really a long time fighting bugs and implementing new features
Hello, i have a script holding a reference to a generated input actions class from the input actions asset.
When i adjust a script during playmode the instance or reference to it seems to be gone.
_inputActions = new InputActions();
Is the code i have for creating an instance.
Could it be this instance is deleted when Unity reloads a script during playmode after adjusting it?
Are there methods that do get called when it's being reloaded to make sure it works flawlesly in the editor too?
Yes, way too many people start game dev with the idiotic idea in their heads that it is 'easy'
you should realistically exit play mode, recompile, and then enter playmode. there are assets which let you hot reload and its more reliable but still there are limitations.
Yeah, i know i can do that but i sometimes like to adjust small things and would like to just make sure the script works after an adjustment
As far as Input Actions is concerned your best bet is to catch the domain reload and disable/enable your action map
Is it a good idea to just put it in OnEnable()? Right now the instance creation and setcallbacks function is in Awake and only the .enable is in OnEnable()
tbh, not sure that will work. I use this
https://docs.unity3d.com/ScriptReference/AssemblyReloadEvents.html
ah ok thanks, i should just generate a new instance in the OnAfterReload maybe?
yep
dang well thats called learning
Maybe pick one at first, either 2d or 3d
Doing both at the same time will be too confusing ig, and 2hrs is nothing like Steve said. But it's nothing for one type of movement. For 2 types it's less than nothing :p
True I think I will start with 3d. And I hope next time the movement will work
A bit more difficult choice, but switching to 2d from 3d is like walkinthepark
So should I start 2d then?
That depends. If you want to do 3d in the future, you can start with 3d (or 2d to get the basics then move to 3d), it's all about what would be more comfortable for you. But if you like 100% sure that you want to do for example only mobile 2d apps, you don't need to know 3d at all
So prepare to learning about quaternions and matrices asap :p in 2d you need only sin and cos.
Can you give some examples where you often need to use matrices?
Shaders as a whole, but right, it's not general programming. I found them helpful to understand quaternions tho
Working on a racing AI using ML Agents. I don't know what I'm doing wrong, I'm implementing what i'm seeing in YT videos almost 1:1 to no avail. What relevant information should I send to get help for this?
#1202574086115557446 and just explain what you're trying to do, show what you tried, and explain what's happening that differs from your expectation.
done, ty
I'm generating a mesh for my voxel grid, but I want my voxels to be able to be multiple materials. Do I have to generate separate meshes for every material?
You can have multiple materials on the same object
You can use a texture atlas and use UV mapping to map the different textures to different regions of the mesh
you could also use multiple submeshes and multiple materials, yeah
I don't want textures, I'm going to be using different shaders so I suppose there's no way to NOT use different meshes is there
like some voxels will be glowy and stuff
multiple submeshes can use multiple materials, as mentioned
If you want different materials there are absolutely no way to avoid multiple draws
How do I generate submeshes
I'm drawing the mesh using the Graphics.DrawMesh. Do I have to use a MeshRenderer for this, or can I just generate separate meshes instead of using the submesh stuff.
I have a script that from time to time stops working, or I guess "updating". It stops working when I make changes in other scripts but starts working again when I make changes in it. I have no idea why it acts like this and it drives me crazy since I've already spent hours trying to fix the problems that this causes. But it wasn't until recently that I understood that this script was the root of the problems.
FYI: The script is a public class that doesn't derive from MonoBehaviour and I do not get any errors from it, whether working or not.
(With "make changes" I mean typing something, anything, and saving).
This is the script:
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable] public class Cooldown
{
[SerializeField] private float _cooldownTime;
private float _nextFireTime;
public bool IsCoolingDown()
{
return Time.time < _nextFireTime;
}
public void StartCooldown()
{
_nextFireTime = Time.time + _cooldownTime;
}
}```
no, you don't need a Renderer with DrawMesh
that's the point of it - to render meshes without a MeshRenderer
Also RenderMesh is the newer API
nono I know
I'm on an older version of Unity
RenderMesh doesn't exist
anyway, I meant that does Graphics.DrawMesh support multiple materials? If so, how do I give them to it
Look at DrawMesh, it takes a submesh index and a material https://docs.unity3d.com/ScriptReference/Graphics.DrawMesh.html
It would be one DrawMesh call per Material/SubMesh
o yea
!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.
long shot, but does anyone know a chess AI which supports, more than normal chess pieces on the board, and a configuarable chess board itself [i.e. missing tiles]?
you mean like 20 pawns for example?
or a bigger board like 12x12
both
I've tried the firebase help discord, but it is so incredibly inactive and unhelpful:
Using firebase with Unity, my client crashes when I try to login.
The conditions that cause this are when someone is already successfully logged in and then someone else tries to login. This 2nd person's client crashes
public async Task<bool> Login(string _email, string _password)
{
try
{
Debug.Log("Bruh 1");
// Call the Firebase auth signin function passing the email and password
var loginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
Debug.Log("Bruh 2");
// Await until the task completes
await loginTask;
Debug.Log("Bruh 3");
User = loginTask.Result.User;
Debug.Log("Bruh 4: " + User.UserId);
DocumentReference docRef = DBreference.Collection("users").Document(User.UserId);
Debug.Log("Bruh 5");
My crash logs never make it to the Bruh 5 debug log, but successfully shows the correct User.UserId. Any ideas?
Check the logs and post the part where it crashes. You may be getting an exception
!logs
I have, I mentioned that at the end
No errors
Also since you await the task, it's a bit weird to use .Result here
var result = await loginTask;
User = result.User;
Does the crash still occurs if you remove the line between logs 4 and 5? Same question with wrapping it with a try/catch and logging if there's an exception
Trying the change to var result = await loginTask now...
It is already wrapped in a try/catch as you see at the top, I just don't show the rest
I can try removing the line between logs 4 and 5 to just be 100% it crashes there
If you start the task in background, you cant use debug.log and other unityengine methods
Ah well I cannot replicate the issue if I remove the line that I suspect crashes because for the correct conditions to be met, someone has to already have logged in and then a 2nd person tries
Do you get any logs?
no crash logs
do you get the debug.logs "bruh " ?
Up to the 4th
See if there's a non-async alternative, even if it freezes the game for a bit, just to rule out a threading issue
Unity will silently terminate a "background" thread that accesses Unity stuff
But as he gets the other debug logs, I guess its not the issue here
What is loginTask actually doing?
pretty sure Debug.Log is one of the few things that can be accessed on another thread with no issue
Not from what I have experienced in the last past weeks
Thats why I am using this thing to actually log in tasks/awaitables on background threads
static public async Awaitable LogQueue(object message, Object context = null)
{
Dispatcher.Enqueue(() =>
{
if (context != null)
Log(message, context);
else
Log(message);
});
await Awaitable.MainThreadAsync();
}
First it authenticates the user's credentials, then accesses firebase to get the user's account info like username, customized character, saved spell loadouts etc then it proceeds to allow the player to the main menu
Id say, the issue is inside that task and you dont get errors because it might be on another thread. try to comment out parts of that task and see if one crashes the whole thing at some point. Just make a simple boolean or something that you can activate to mimic the code being commented out
this is just weird. why do you join the main thread then do nothing? what does the actual Log method do? Debug.Log can be used from other threads, though the context parameter might be an issue
I can await that log in my threads, so I get the correct udpated values from unitys mainthread queue before continueing in my background thread
yeah the context parameter will definitely cause problems on other threads, but the non-context one is fine
your method ends after you wait to return to the main thread, so there's nothing happening on the main thread there, you might as well remove it
has anyone here used the Simple LUT Adjuster from Jeff Johnson?
I enqueue my method to the mainthread, but the task would continue if I dont wait for the mainthread, got it?
the MainThreadAsync just means the rest of the method after that runs on the main thread, it does nothing if the rest of the method is empty
You know that I await for the Debug.LogQueue...
that doesn't matter
what you wait for inside an async method has no effect on its callers
if I await for the async method to be finished does
if your method runs on a worker thread but is awaited from the unity thread, the caller will return on the unity thread
i honestly don't even see the point in wanting to await the LogQueue method in the first place. it should just be a normal synchronous method that enqueues the log call and that's it
Anyone know how to fix this?
If you have a async background task and want to log a value, you wont get that log until the mainthread is being done. But if I want a specific order of the logs to work along the system for clarification, I await the log, get the correct value and then continue.
change your IDE settings? that's just a style warning
wdym you await the log? that isn't waiting for the log to print, that enqueues the log to your dispatcher, then waits until it can continue on the main thread then does nothing.
there is no guarantee here that the log has even printed yet, the only guarantee is that it has been enqueued to your dispatcher queue
So if I have an async awaitable MethodA and inside that I await the LogQueue, it is not waiting for the mainthread before continueing MethodA?
if that is what you want to happen, why is that the responsibility of a method that is just supposed to queue logs to print?
Because I want the MethodA to have a correct order of logs instead of relying on the mainthread being done in parallel to the background thread and spitting logs in wrong order coming from different tasks
but even still, awaiting MainThreadAsync does not guarantee that your log has actually printed by that point as that is entirely up to how and when your dispatcher prints the logs
public async Task<bool> Login(string _email, string _password)
{
try
{
// Call the Firebase auth signin function passing the email and password
var loginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
// Await until the task completes
var result = await loginTask;
User = result.User;
Debug.Log("Bruh 4: " + User.UserId);
/*
DocumentReference docRef = DBreference.Collection("users").Document(User.UserId);
Debug.Log("Bruh 5");
string playerUsername = "";
var snapshot = await docRef.GetSnapshotAsync();
Debug.Log("Bruh 6");
if (snapshot.Exists)
{
Dictionary<string, object> userData = snapshot.ToDictionary();
playerUsername = userData["name"].ToString();
}
else
{
Debug.Log("Document does not exist!");
}
LobbyNetwork.FireBaseUID = User.UserId;
//LobbyNetwork.FireBaseToken = await auth.currentUser.TokenAsync();
_signInMenu.SetSignInLocked(true);
LobbyNetwork.SignIn(playerUsername);
_characterMenu.LoadCharacterFromDB();
_spellSelectMenu.LoadSpellsFromDB();
*/
LobbyNetwork.FireBaseUID = User.UserId;
_signInMenu.SetSignInLocked(true);
LobbyNetwork.SignIn("Nate");
_characterMenu.LoadCharacterFromDB();
_spellSelectMenu.LoadSpellsFromDB();
}
``` ok well this still crashes so I guess I'm still searching lol
I still think, its your loginTask, causing issues
From what I experienced, it is exactly doing that, guarantee that I get the correct order
The first one logs in the wrong order. It fires test me before the enqueued log. In this case, its expected, but I have nested tasks where the logs got messed up and I wanted to have a clean understandable logging of what is going on.
await Debug.LogQueue("AR Supported: " + arSupported + ". Fallback to non tracked runtime.", this);
Debug.Log("Test me");
This one logs correctly one after the other
await Debug.LogQueue("AR Supported: " + arSupported + ". Fallback to non tracked runtime.", this);
await Debug.LogQueue("Test me");
This especially was an issue, when I needed to access unityengine parts in background, so I had to enqueue and wait for the mainthread , then continue
that's not really related to you awaiting that method though, that's because of the fact that you are queueing your logs with a queue then presumable dequeueing them in that same order on the main thread
And also, the object, as you mentioned, was causing issues, so both issues made me do the enqueued log.
Would using a TCS solve this? Maybe the timing issue at least
Task LogAsync(string message)
{
TaskCompletionSource tcs = new();
Dispatcher.Enqueue(() =>
{
// ...
tcs.SetResult();
}
return tcs.Task;
}
how are you calling this?
Whats the benefit of this one? Curious to test it
and we return to my original point of making that method async is entirely pointless. the dispatcher queue and how that is handled is what makes your logs print in the right order, not awaiting that method
that would actually allow you to await the log printing in the console rather than just awaiting nothing
But Awaitable.MainthreadAsync is awaiting "something", isnt it?
Allows you to create a task you have control over, where you can set whether it completed or failed with an exception
Completing the task in the Enqueue method will stop the caller from awaiting. At this point your log should be printed and the execution will resume past the await
So the Awaitable.MainThreadAsync() is not actually awaiting for mainthread and then continue?
okay fine, i'll rephrase: rather than just awaiting nothing useful.
because awaiting to join the main thread does not guarantee that the log has printed as i've explained multiple times now
But should enqueued logs not being printed by then, because the joining happens at the next cycle?
It is, but since you already enqueued the log "command" to the dispatcher, and have nothing after the await, it's switching to the main thread for nothing
am i just going to need to keep repeating myself here?
#archived-code-general message
This would ensure the log is ran on the main thread, if I understand the API correctly
await Awaitable.MainThreadAsync();
Debug.Log("hello", obj);
And what about the method that is awaiting this logasync method? Would it also be joining the mainthread or just waiting for the logasync to complete and then continue in background?
And this totally makes sense now rechecking the docs too. This would remove my entire dispatcher part.
The caller's context won't switch to the main thread IIRC, each async method has its own context
Okay, so using your code snippet up there would as desired "pause" the caller and then continue
Given that you await the task, yes
but why would you want the caller to be paused for that? if the only point was to make the logs print in the correct order, then you've got that with the dispatcher queue, like that's the whole point of the queue. the async part of that method is irrelevant for that with the dispatcher there
I just removed the dispatcher enqueue entirely and just used the awaitable mainthread method to log after that. Still need to wait for the log, because I want, as said already, my logs to be in correct order. Task doing something in background, starting another task that checks on whatever, doing some log too. If I let them all just log together on the mainthread, it would just be a random order of logs at whenever the mainthread is cycling. Thats why I was waiting for the mainthread in the log. And as expected its working as before, but makes more sense now as you guys stated to not await and then do nothing. Thanks for your input and suggestions!
I guess, telegram might provide some API to access from wherever this documentation is coming from.
well now you're just potentially slowing your code down even more when you continuously hop from background threads to the main thread. and even then, why not just do the work on the main thread in the first place if you don't care about needing to do so? the dispatcher already controlled the order of the logs as i've described to you countless times at this point. you just refuse to understand that for some reason, all you needed to do was make that LogQueue method return void and no longer be async and it would have worked just as well as it already was, but without the pointless awaiting
I am using several frameworks which only provide async methods for example. But as thankful I am for you explaining things, I think this conversation has reached its limit of objective communication. Thanks again and have a great evening/day/night π
i'm not saying you can't use async for other things. i was simply pointing out that LogQueue has really no reason at all to be async if you were just enqueueing the logs to be printed on the main thread
Why do you think that? I've made some workarounds to be able to proceed around my DocumentReference docRef = DBreference.Collection("users").Document(User.UserId); line, which is my suspected crash point.
But now it proceeds to two other spots that call something very similar and crashes there. Commenting those out allows me to proceed without crashes
Did you log the User and also the collection? Maybe something is null or invalid?
When I try to log the collection, it crashes there :/
User works fine because I can get User.UserId
Wait, you can get the userid from the user in document in the collection, but you cant log the collection itself?
// Call the Firebase auth signin function passing the email and password
var loginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
// Await until the task completes
var result = await loginTask;
User = result.User;
Debug.Log("Bruh 4: " + User.UserId);
I get this log, but if I were to do Debug.Log(DBreference.Collection("users")); it would crash
Ah, the login task is providing the user, okay, my bad. So, try to cut it into parts. Log your dbreference, is it !null?
Nope, I tried it earlier, it is fine :/
What is DBReference?
public FirebaseFirestore DBreference;
oh wait, one sec
private void InitializeFirebase()
{
Debug.Log("Setting up Firebase Auth");
//Set the authentication instance object
auth = FirebaseAuth.DefaultInstance;
DBreference = FirebaseFirestore.DefaultInstance;
}
And again, this works if only one account logs in. It is once the 2nd one logs in while the first is still logged in that it crashes
So it could be some sort of one-time-use session token being used but I have no clue what I'm doing here lol
Are you using the same user for the login?
Nope
Printing the Debug.Log("Bruh 4: " + User.UserId); shows a the different users
Is it always the second user that crashes it? So is it the same user all the time or is it possible to login user2 and then crash on user1?
Doesn't matter what order I log in, it is always the 2nd user to login. I've played around with a handful of accounts just to make sure it wasn't some weirdly specific combination lol
There seems to be a debug log level, you can change. Maybe use this in debug to get more information?
you've got a try/catch in your code, but what are you actually doing when you catch an exception? and are you catching all exceptions or only a specific kind?
At first it was only firebaseexpections, but I just did a generic:
try
{
//code
}
catch
{
Debug.Log("ERRRROORRR");
}
well that's not very helpful for debugging purposes. why not catch (Exception ex) and then print the actual exception?
It didn't even print that debug log tho
try to catch a specific type and try again. And enable debug log, maybe its giving you some info
I also tried catch(Exception e) and it didn't catch.
Am I wrong to assume that just doing a basic try/catch wouldn't catch everything?
try
{
}
catch
{
}
And my current one is a FirebaseException
Did you enable the logging to debug for firebase?
Not yet, I will after I'm done eating!
Do you guys know what version of C# will be used for unity 6?
I found the solution, figured since you invested time to help me that you'd be interested!
Had to add this in my initialization:
DBreference.Settings.PersistenceEnabled = false;
Found someone else with a similar obscure problem on a github issue page...
The .net modernization is not expected until unity 7 (or whatever they decide to call it) so there won't be any changes in the c# version until then
Oh okay thank you
what's the best way to make an object follow another object's movement but with a multiplier?
so if object A moves 10 units, object B would make the same movement at half speed and move 5 units
Multiply the speed of the object by a scalar value, such as 0.5 for half the speed.
For following, entirely depends on how you're moving things. You want a straight line? Just move it towards it via MoveTowards(...)
yeah, probably should have mentioned that it doesn't use velocity
trying to make a parallax background
here's the (relevant) camera movement code
if(Vector2.Distance(targetPos, transform.position) < 1f && Vector2.Distance(targetPos, transform.position) > 0.01f){
speed = 1/Vector2.Distance(targetPos, transform.position);
} else {
speed = 1;
}
if(Vector2.Distance(targetPos, transform.position) < 0.01f){
transform.position = targetPos;
}
don't remember the way to make that c sharp formatted
Multiply your final speed by some scalar value
But if you want it to be a % of the target speed, it really should just take the speed of the target rather than calculating its own and multiply against that?
I don't understand what you're trying to say
I want the object to move at a fraction of the camera's movement
You want ObjectB to move the "same movement" as ObjectA but half the speed. So get the speed of ObjectA and multiply it by half.
i thought there would be some shortcut for this but i guess if that's the only way, i'll do it
it's just annoying because of the code that adjusts the camera not based on speed
so i'll have to recreate that for the other object
couldn't you just do this in LateUpdate?
Vector3 pos = transform.position;
pos.x = target.position.x / 2f;
transform.position = pos;```
how do i make dynamic rigid body not flip in unity 2d i want my charechter to not fall and flip
Can you elaborate what you mean by that?
also please ask only on one relevant channel
Hi! I'm trying to make sort of a modular system, with a class for each different module. I have an issue though, that if a class inherits from another class, I don't seem to be able to have that class have some variables different from the parent class? Example:
public class ModifierTemplate : MonoBehaviour
{
public int multMultiplier = 0;
public int numMultiplier = 0;
public int flatMult = 0;
public int flatNum = 0;
public bool addNumberToNum = false;
public bool addNumberToMult = false;
public void triggerModifier(GameWheel wheel, NumberTemplate number)
{
wheel.mult += flatMult;
wheel.num += flatNum;
wheel.mult += (wheel.mult * multMultiplier);
wheel.num += (wheel.num * numMultiplier);
if (addNumberToNum){wheel.num += number.number;}
if (addNumberToMult){wheel.mult += number.number;}
}
}
public class x2Mult : ModifierTemplate
{
}
In this example, I wan't the x2Mult class to inherit the modifiertemplates triggerModifier function, and it's variables, but I would want for the "multMultiplier" variable of the x2Mult class to be different from the modifiertemplates class.
How do I do that?
Don't crosspost please
just set it to a different value in the inspector of the X2Mult class
I'm trying to do it in the code, and it's not letting me
otherwise
public class x2Mult : ModifierTemplate
{
public override int multMultiplier = 1;
}
Oh, I need to use the override! Thanks! Massively helpful, I didn't even know override existed.
and
public class ModifierTemplate : MonoBehaviour
{
public virtual int multMultiplier = 0;
Thanks!
Uh, it's telling me that serialized fields can't be virtual?
oh, try this
public class ModifierTemplate : MonoBehaviour
{
public int multMultiplier = 0;
...
public class x2Mult : ModifierTemplate
{
public new int multMultiplier = 1;
}
I think that works, yes. Though rider is telling me the x2Mult's "multMutliplier" variable isn't being used, is it supposed to be like that? Is that a quirk of Rider or does it mean that it won't work?
that's rider gatekeeping
Thanks!
one question, why is ModifierTemplate not abstract?
I'm sorry, what does abstract do?
oh dear, sounds like you need some basic C# learning.
abstract means that the class itself cannot be instanced but classes that derive from it can. It's a kind of protection ideal for 'Template' classes
Aha, that sounds like exactly what I'll need - I'll make the ModifierTemplate abstract then.
then you should be able to make the variables virtual and the method virtual as well
As for the learning bit, that's why I'm on this discord, isn't it? I will admit though, my knowledge of C# is quite holey, as most of my learning has been from figuring it out myself and using stackoverflow
Thanks, I'll do that then
tbf, we are here to help with Unity problems not basic C# ones
Yeah, I get that - I thought I knew basic C# but evidently not that well. I get by though, mostly using stack overflow
Oh, and it still complains that serialized fields cannot be made virtual when I set the class to abstrac
I find that very odd, wait one
Virtual would be for methods or properties.
If you wanna apply a different formula then itd make sense to have a virtual method and override the actual method implementation in the x2 multiplier class. Otherwise if this value is just supposed to be double, you dont need another whole class for that.
I do need another class for it, because of how my system is built, but for the specific x2Mult class I would only need to make the "multMultiplier" field have a different value
There will be other classes inheriting from the modifierTemplate class that will need a different formula/method though
lol, the kinda stuff you wont get from Stack Overflow
public abstract class Template : MonoBehaviour
{
[field: SerializeField] public virtual int Count { get; set; } = 0;
}
...
public class DerFromTemp : Template
{
[field: SerializeField] public override int Count { get; set; } = 1;
}
I guess you could change the formula here and just insert an extra 2 * ... but it truly isnt needed.
Never would have guessed that - thanks though!
Those are properties, I wrote above you would use virtual with either methods or properties. But the use case here seems wrong because this would imply you're defaulting it to another value. Your initial script defaults it to 0. 2 * 0 = 0
Yes, I am defaulting it to another value
And again because these are monobehaviours you dont need another script for this. You assign the value in inspector. The only thing this changes is the default value when you create the script
No, I do not assign the values in the inspector - These classes will only be created at runtime, in the code
Is there a reason you're using monobehaviours then?
then you cannot use MonoBehaviour, they cannot be new()'d
Oh, I can't?
I assumed you were planning on using AddComponent at runtime, which isnt common at least from what I've done
you can only instance a MonoBehaviour using AddComponent
Thinking about it, I suppose I don't need them to be monobehaviours - that was just me not thinking about it
Yea this could probably just be it's own plain c# class and youd save a bit of performance if theres a ton of modifiers
and, it will follow the rules of C# not the rules of Unity
Yeah I did that now
Though I still do find it unnecessary to create a whole new class just for a default value to change. When you create an instance of that base class, all those values are 0. Surely you plan to assign some values to those modifiers. Maybe itd be better if you just change the formula in the x2 multiplier class instead
It is necessary because of how other aspects of the game is structured. I could restructure all of the other things, but I can't be bothered. Besides, it's a really simple 2D game, it will run on a potato anyway so performance isn't an issue
That last point was less about performance. It's more about how you're going to be assigning a value to this class somehow when its new()'d. Maybe in the constructor, maybe just by changing the public variables. If you dont do this then well all the values are 0 using the base class.
Now if you want to use the x2 multiplier class, this would imply you're now using the default values. If you assign the values like you will be doing using the base class, then theres no point in having a different default value.
And if you're creating an instance of this derived class, you already know it's supposed to be a 2x multiplier so you could just assign it larger values. Or use the constructor, pass it in a value, and it automatically multiplies it by 2
Anyone got a good tutorial for a rts style system
Way too broad a question, what part of RTS style system?
Some general overview, I liked: https://medium.com/codex/making-a-rts-game-1-placing-buildings-unity-c-c53c7180b630
Rather long and textual tutorial though, and not at all best practices, just basics.
Just creating good pathfinding, like in SC2 is a full time job in and off itself.
If you want to make Supreme Commander/BAR type game, you need to do things very different.
So we don't really have a way to give you a 'good tutorial'.
when i run webgl build and start server using netcode for game objects, it gives error:
Exception: WebGL as a server is not supported by Unity Transport, outside the Editor.
#archived-networking
But also, that is accurate. you cannot use the unity transport on webgl unless you use the netcode for gameobject 1.2.0 version (or higher) with the unity transport version 2.0.0 (or higher). so presumably you are using an older version of one of those packages
oh and don't crosspost. you originally posted in networking whihc was the correct place to do so
i can only see 1.1 in package manager for netcode for gameobjects
what version of unity are you using?
2022.3.49f1
show what you see in the package manager then
that's 1.11 not 1.1
and last time i checked 11 > 2. so the issue is likely the transport version
Oh, i thought 1.2 > 1.11, my bad
no these aren't decimal numbers, they are semantic versioning numbers.
i am also using 2.3 of unity transport still getting that error
isn't the latest version of the transport 2.2.1? π€
no its showing me 2.3
huh, docs must not be up to date then. in that case, provide that information in your message in #archived-networking and wait for someone to answer you there
Im looking for just something to get started. Just looking for like camera conttrol and panning and unit selection. Not pathfinding yet, since i know like u said, its super complex if (if u want sc2 level)
Well that tutorial from Mina will give you a tiny base with resources, movement, enemies, basic pathfinding and stuff like that.
Personally I liked it, and couldn't find much else on a full tutorial on the basics of RTS.
Ok thank you!
Is anyone in here using the latest webrtc pre package and knows the fix of the missing plugin registration causing this on build?
The type or namespace name 'WebRTC' does not exist in the namespace 'Unity' (are you missing an assembly reference?)
I am on apple silicon, which seems to be causing the issue
And here seems to be some kind of fix in previous versions, but cant really get the gist of what to touc here: https://github.com/Unity-Technologies/com.unity.webrtc/pull/568
Quick question for the AI folks:
Are there AIs that I can integrate into my Unity project to look at the code and answer me questions like "which script does such thing?", etc?
I basically want to avoid the problem of returning to old projects and not remembering what things do what
at the moment, only looking at scripts would be enough for now. Extras are welcome thought π
I'm also willing to write descriptions in my scripts (as commented code) explaining what it does if it's useful for the AI
not likely, you'd probably have to do more work than is worth.
Most good code is self-explanatory, if its not you have a bigger issue.
Comments are good but they are more useful imo when they describe WHY you did that code instead of What is that code doing.
tbh I cannot even imagine what it would be like to not remember my own code
Im currently adding a moba like progression to a prototype im making, with items that increase your stats and add special effects to your attacks or abilities, im thinking ill implement this by keeping an inactive prefab of each attack and ability on the player as a child, and duplicate them when i need to actually spawn them, and whenever an item is bought that adds an effect, i add a script that applies said effect to the inactive prefabs at runtime
how viable is this solution?
Anyone got any tips for adding a webgl into a web app built on rust with dioxus?
It does not matter what you built the webapp with, at some point you will have a html page which you can integrate the unity index.html into
That's a relief haha
tbh I'm amazed that anyone building a web app would not know that
I'm brand new to this haha taking an existing web app and adding a game that I made as a proof of concept and just for practice with it all
Way beyond my wheelhouse, but I've learned a lot and it's fun lol
My game has some calls to Camera.ScreenPointToRay(Input.mousePosition) that is spamming up the console when I start with "Screen position out of view frustum (screen pos inf, inf) (Camera rect 0 0 2560 1440)" messages until I click on the game window. It's not an exception, it's just an error log message, but it's a little annoying. How do I get the "view frustrum" from the camera..? Or do I just need to check for Input.mousePosition.x or .x == infinity? I couldn't find what I need in the API docs for Input and Camera
(do I just compare mouse position to Vector3.positiveInfinity?)
could you show that line ?
(I just added the lines at the top with all those guard clauses)
The line in question is the Ray ray = Camera.main ... line
Input.mousePosition reports as positiveInfinity until I move it somewhere in the game window.. after that it's fine
did you change anything on the camera?
Whatcha mean? I changed lots of things π but I'm using cinemachine for some custom zooming/tilting
can i see the main camera component RQ when this error happenes
sure, lemme comment out those guard clauses.. sec
this is likely just a quirk of unity not capturing the mouse for the game view until the game view is manually focused
This is kinda what i'm thinking?
oh okay position all looks good, so yeah prob what box said but I have no clue it doesn't happen to me
checking this property should be enough i would think: https://docs.unity3d.com/ScriptReference/Application-isFocused.html
it only happens if I start the game in Scene view, btw
I could do that too.. although I'm not sure if that's gonna have weird effects if the user has their mouse in the middle of the screen then alt tabs out.. like.. I'm doing a lot of the input handling manually for map drag/tilt
map drag/scroll wheel = pan & tilt
wrap it in conditional compile so it's only included in the editor
well, it might happen in the web too.. in fact it might almost be guaranteed to happen in the web? I'm not sure if the applet is gonna have focus by default
I'll check into it.. I might need to have the user click on the applet to start anyway so I am guaranteed to capture input
don't crosspost
sup gang
would it be better to have a for loop for this?
//Set Verified Decks List
_allDecks = decksToLoad;
_totalPages = Mathf.RoundToInt(_allDecks.Count / 5) + 1;
Debug.Log("Total Decks: " + _allDecks.Count);
Debug.Log("Total Pages: " + _totalPages);
//Instantiate all decks buttons
foreach (DeckSO deck in _allDecks)
{
//Set page transform,
//5 decks per page
Transform pageTransform = transform;
int currentDeckIndex = 0;
var butt = Instantiate(_deckButtonPrefab, pageTransform);
butt.GetComponent<Button>().onClick.AddListener(() => SelectDeck(currentDeckIndex));
butt.GetComponent<Tooltip>().SetToolTipMessage(deck.Description);
}```
I have a list of decks, which it will create a page for every 5 decks
as oppose to what?
for each page, it will instantiate a button (up to 5) for each deck
the only thing I would change mainly is the AddListener and also make it its own class that has already those as props
I can see that. But you can skipp add Components if you already had those assigned as props
and AddListener, I rather use an actual method assigned to it so I can clean it up
my add listener is fine
I want to focus on the ID
every time I instantiate a deckButton in the list, I want to assing an ID to it
so whats stopping you?
you have to increase the index you can't define it in the loop or you keep overwriting it with 0
I'm trying to figure out how to get the index
oh
so I need to make an int, outside of the loop
if you plan on increasing it each iteration, sure
yes
also why not just use a for loop in that case
okay let me see what I can do
exactly
that's what I was asking
xD
if it was better
I wasn't sure why you asked if a for loop was better sorry
^ all good
let me try this with whawt I have and
I'll come back with results xD, good or bad
When you resize the browser, is there any way to hook into unity? The canvas I'm using is getting physically shrunk but I'm not getting changes to Screen.width or height
messy, but it works
@rigid island
void LoadAllDecksInList()
{
int deckIndexInLoop = 0;
List<DeckSO> decksToLoad = new();
//Clear All Pages and Decks List
_allDecks.Clear();
_deckPages.Clear();
foreach (Transform page in _deckPagesHolder)
{
Destroy(page.gameObject);
}
//Add all existing decks
foreach (DeckSO deck in CardsLibrary.Instance.BasicDecks)
{
decksToLoad.Add(deck);
}
//Also load custom decks here
//Verify if decks are valid
//Set Verified Decks List
_allDecks = decksToLoad;
_totalPages = Mathf.RoundToInt(_allDecks.Count / 5) + 1;
//Instantiate all pages
for (int i = 0; i < _totalPages; i++)
{
var page = Instantiate(_deckPagePrefab, _deckPagesHolder);
page.name = $"Page {i}";
_deckPages.Add(page);
}
//Instantiate all decks buttons
foreach (DeckSO deck in _allDecks)
{
Transform pageTransform = _deckPages[Mathf.RoundToInt(deckIndexInLoop / 5)].transform;
var butt = Instantiate(_deckButtonPrefab, pageTransform);
butt.transform.Find("Deck Leader").GetComponent<Image>().sprite = deck.DeckLeader.LeaderImage;
butt.transform.Find("DeckName Text").GetComponent<TextMeshProUGUI>().text = deck.DeckName;
butt.GetComponent<Button>().onClick.AddListener(() => SelectDeck(deckIndexInLoop));
//butt.GetComponent<Tooltip>().SetToolTipMessage(deck.Description);
butt.GetComponent<Tooltip>().SetToolTipMessage($"Index: {deckIndexInLoop}");
deckIndexInLoop++;
}
_currentPage = 0;
UpdateSelectedDeckPage();
}```
void UpdateSelectedDeckPage()
{
foreach (var page in _deckPages)
{
if (page != _deckPages[_currentPage])
page.SetActive(false);
else
page.SetActive(true);
}
_currentPageText.text = $"{_currentPage + 1}/{_totalPages}";
_nextPageButton.interactable = _currentPage + 1 >= _totalPages ? false : true;
_previousPageButton.interactable = _currentPage == 0 ? false : true;
}```
they're instantiated properly and I can select them
which is nice C:
nvm
the listeners are not being added properly, one sec
I'll try with this forloop, if not I'll do it outside like you said
it's supposed to be 5... :/
which I find weird
cause the index in the tooltip message is assigned correctly
see, it's getting "5" in the index
Can someone explain how you're supposed to query an input on a specific device using the new input system?
iirc this an issue because you're doing the lambda
yes i was going to suggest to capture the variable first
in what way?
Well normally you would use events instead of polling
thats the main benefit of inputsystem
π
I have an implementation question that I'd like some guidance with: I have Characters with a set of abilities, where each character is a prefab, and the character's abilities are also represented as a list of prefabs within the character prefab. My problem is as follows: In the general case, each cast has an individual cooldown, but I'd like for my implementation to handle the case that different casts share a cooldown. Some relevant code snippets:
public struct CastContainer {
public Cast castPrefab;
public int cooldown;
public int timer;
// ...
}
public class Character {
public CastContainer[] castContainers;
// pseudocode regarding cast:
void FixedUpdate() {
if (canAndWantToCast(castContainers[i])) {
Cast(castContainers[i].prefab);
castContainers[i].timer = castContainers[i].cooldown;
}
// ...
}
}
So, in the general case, each cast handles their own cooldown. However, I want to flexibly handle the case that, in some fashion, I've told my game that if cast0 OR cast1 are casted, I want both to go on cooldown. How might I elegantly write this? I can think of ways off the top of my head, but nothing that doesn't feel hacky π¦
One way that comes to mind is firing an event or calling a function that will happen on all casts, that event/func could take a "CooldownType", enum or ID, and if cast0 and cast1 have the same ID or "type" when that event is fired, they can respond with starting their own cooldown - for something like cast2 to not respond in the same way, it would only need a different ID/type than cast0 and cast1 would be using
Hello! I am trying to implement a stepOffset to my controller. I am currently using Modular First Person Controller from JECASE on asset store, but it does not have step offset custo. I would like to continue using this controller as I am pretty deep into development. I cannot add an additional character controller or else my player flys up. I have been at this for the past hour and dont want to resort to slanted planes. Any help appreciated!
you could try getting the move direction, and generating a raycast a little bit forward, and then directly down at the knee level
I can draw something if that doesnt make sense
and the maybe compare the world height of whatever that raycast hit, with the controller's world height
Thanks! I will work on it more tomorrow and try and implement this into a script!
{
Vector3 cameraPosition = Camera.main.transform.position;
Vector3 playerPosition = playerTransform.position;
float followThreshold = 3.0f;
float verticalDifference = playerPosition.y - cameraPosition.y;
if (Mathf.Abs(verticalDifference) > followThreshold)
{
// Start following the player smoothly by locking onto their Y position after the threshold is crossed
float targetY = playerPosition.y;
cameraPosition.y = Mathf.Lerp(cameraPosition.y, targetY, Time.deltaTime * 5.0f);
Camera.main.transform.position = new Vector3(cameraPosition.x, cameraPosition.y, cameraPosition.z);
}
}```
the slower the player moves upward, the more it jitters. anyone know why it does that? I tried making it move fast and it doesn't do that, only when it levitates slowly up
For starters, that's not a correct way to use Lerp.
Which might or might not be related to the issue.
would SmoothDamp work?
Probably. Or just MoveTowards
We need more context
Also why the new vector3 at the end there?
I changed it. I used cameraPosition.y and assigned it the MoveTowards function and it somewhat works, just gotta tweak the speed
ty btw, Dlich (dont wanna ping lol)
Using context steering, how can I make an enemy reach its target behind a wall? Whenever I try it just gets stuck facing at the wall.
Basically I have it set so that the enemy uses a dot vector between the target and each direction and then gives said direction a positive weight. Then it raycasts to each direction to check for obstacles, then if so gives it a negative weight. The substraction from the positive and negative result in the direction to move. Whenever the target is behind a wall the weights on the direction to the target just cancel each other out and the others just stay at 0
Hi, guys! I am working on animation for my player and have a question. I am using WASD input to set the proper direction animation. However i think it is better to check the direction movement of the player and set animation in accordance with it. How can i determine player direction using this input?
movementX = Input.GetAxis("Horizontal");
movementZ = Input.GetAxis("Vertical");
2D or 3D? If 2D, top down or sideways? If 3D, first person or third person?
3D, FPS
If vertical axis is > 0 then movement is forward, if < 0 it's backward, and horizontal > 0 is right and < 0 is left
thanks!
im creating a scroll rect pagination UI
while i was dragging it, lets say im dragging 20th elements
if i went to certain threshold, the UI spawned 21-30th elements, somehow my view will jump to 30th
like automatically went to the latest(bottom) element
how can i prevent that?
you using unity ui or uitoolkit?
uitoolkit is much much easier to use for this kind of stuff
our team was using https://assetstore.unity.com/packages/tools/gui/recyclable-scroll-rect-optimized-list-grid-view-178560?srsltid=AfmBOopHJD5SD4tRE_npnWfUZ9a9N-PHJJa9FVZleCkytl7s9ZoCEZ9E , and we modified some contents
but then it was sprawling out of control
annnnnnnd we need to fix it or find something better
I would really recommend uitoolkit, it's much more flexible and, more importantly, much easier to customize
1- it's 'etc' not 'ect'
2- this is a code channel and that is not a code question -> delete and ask in #π»βunity-talk
hi, i was wondering how i can include a separate .net project in my assembly-csharp.csproj? unity seems to regenerate the project file and remove my project reference every time.
and perhaps more specifically, is there a way to have a custom solution layout? i would like to place my projects in src/ProjectName while still keeping Assets in the root of the solution
you cannot nest projects within projects
that's not what i'm asking about?
that is exactly what you asked
i mean i'm not here to argue semantics. it's just not what i'm asking.
let me know what confuses you and i can clarify
this ' how i can include a separate .net project in my assembly-csharp.csproj'
a project reference is a basic .net functionality
i'm fairly certain they are referring to a project reference like you would normally do in a non-unity project, not actually nesting the project.
it's not exactly something unity currently supports. you'll need to build that other project as a dll and include the dll in your unity project
ah, missing the word reference
that sucks
well, i guess how can i include the dll as a reference without it being overwritten
put it in a folder called Plugins in your project
you put the dll in your actual assets folder, then if you are using assembly definitions in the project you give those a reference to the dll. you do not modify your csproj file or its assembly references from within your IDE as unity controls that.
if you are not using assembly definitions in your unity project then simply including the dll in the project is enough
as a .net dev this is a nightmare lmao
yes well hopefully with the switch to the coreclr in the next couple years it will be a more normal process
personally what I do, is have my source files in folders external to Unity. I create symbolic links into the Unity projects and I use links to them in my .Net solution projects to get them into my solutions for creating dll's, that way I have one code base I can work on both inside and outside Unity
related-ish, how could i create a modding api (like an IMod interface) that the game can then load? my idea was to let users compile their own project using the modding api as a nuget package and place the resulting dll imply in MyGame_Data/Managed, which i'm hoping is then loaded by mono. i'm just not sure what to do from there.
Why does converting to and from json make my actions work, but when I use the commented line nothing happens?
This is the new input system btw
I'm using XR and both controllers are using different users.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’
Visual Studio (Installed via Unity Hub)
β’
Visual Studio (Installed manually)
β’
VS Code
β’
JetBrains Rider
β’ :question: Other/None
oh yeah btw im new so can i get help on like how to fix bugs and ask for ideas?
only after you've done due diligence at searching google for a solution to common issues
ok and 2 more questions; what should i start with 2d or 3d, and what can i use for pixel art(for free,im poor)
both apply the same exact concepts, doesn't change much in those terms. Also there are plenty of free assets, nothing stops you from getting those to start with
check places like asset store and kenny
yeah but im trying to but a little bit more effort because i know how to acctually draw
so don't you have an app to draw already?
just export it to unity
they have plenty of software out there for pixel art
i hand draw
a series of frames like any moving picture yes
Unity has its own Animation tool you just put the frames
oh ok so any other things i need to know?
would suggest you go through the !learn pathways, start with the Essentials it shows you a lot of the tools esp 2D
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
they also have tons of other 2D specific lessons but would do essentials and go from there
ok thanks for the info
I've recently incorporated object pooling into my game to improve performance, so it's new to me. I need to change the sprite of one of the objects that's currently in the pool while the game is running. If there's a hundred gameobjects, I don't know if it would make sense for me to do a loop to change the sprite of all those game objects (could cause a lag spike?), or if I'm better off just making an entirely new pool with game objects that use the different sprite. Does anyone have suggestions on a best practice for this scenario?
Just change it when you unqueue one.
I guess I would have to store the new sprite somewhere, and everytime an enqueue occurrs, do an if statement to see if the current sprite matches the new sprite, if it doesn't, change it to the new one?
yeah the point is that you only really have to change them when you're just about to use them. The point of pooling is to rid the overhead of spawning an entirely new gameobject and instead use an existing one. Don't change many at once, only when they're needed.
yeah, sounds about right to me.
Makes sense, thanks guys.
if I'm getting a total editor crash that traces to native Unity C++ code, is my only option to open a bug report? i assume those modules are all closed source
Tried this and unfortunately does not work
sup gang
public async void CreateRoom()
{
// Check if player is in a lobby already, if so quit it
RoomFound = false;
try
{
var options = new SessionOptions
{
MaxPlayers = 2
}.WithRelayNetwork();
var session = await MultiplayerService.Instance.CreateSessionAsync(options);
RoomFound = true;
_currentSession = session;
session.PlayerPropertiesChanged += UpdatePlayerStatus;
session.CurrentPlayer.SetProperty("PlayerName", new(AuthenticationManager.Instance.PlayerName()));
session.CurrentPlayer.SetProperty("PlayerReady", new("false"));
session.CurrentPlayer.SetProperty("LeaderID", new("-1"));
await session.SaveCurrentPlayerDataAsync();
LoadAllDecksInList();
//_hostNameText.text = AuthenticationManager.Instance.PlayerName();
_lobbyRoomCodeText.text = session.Code;
}
catch (SessionException e)
{
Debug.Log(e);
}
}```
I have this code to create a lobby, which is an "Async" void
so I can use await, try and catch
what if, from another script, I call this function
It'll execute, but you cannot await it from the calling mehod
(since it does not return an awaitable type, like Task or Task<T>)
Exceptions will not be bubbled up either (since it's when you await that the runtime checks if the an exception occurred), but you're covered on that since the whole contents of the method is guarded with a try/catch
If you want the caller to be able to await your CreateRoom, and you want it to tell the caller if the creation was successful, then make it async Task<bool> and return the result.
I should make a function here, and call it from my actual CreateRoom()
π I see
so make this a task
that returns a bool
and here
I could have the await and it will work?
That method isn't async so you cannot await in there
Eh, I would not recommend using both async/await and coroutines together. They both (more or less) do the same thing, stick to one or the other.
Ideally you'd just use async/await for everything, or coroutines for everything, not both. If you have some foreign code that uses a different mechanism, wrap it into a task/coroutine.
yes, this is a different script
LobbyRoomManager.cs
MainMenuUIManager.cs
I don't get what you mean by "Wrap it into a task/coroutine"
but yeah... they're 2 different scripts
I guess you could do a custom coroutine type that starts an async task and periodically checks whether it's finished, but it's indeed better to stick to one of the two systems exclusively
Make a decision first, do you want to use tasks or coroutines?
I have never used tasks
so I don't know
whatever you recommend I'll try it
I normally use coroutines, a lot
Async/await is task.
If you decide to stick to coroutines, then turn all your existing code into coroutines, no async/await. If you have foreign code that uses async/await, wrap them into your own coroutines.
well I rather keep my Task
I want to keep this task
Then I would recommend use task for everything, including rewriting your existing coroutine code into tasks. Mixing the two will just lead to problems later down the line.
Well, it has already led to problems, as the one you are having right now.
yeah...
so I should turn my coroutine into a task
I'm down for that
You can work on rewriting you existing coroutine code into async/await, and you won't have the problem of mixing the two anymore.
that... sigh
what do you think of this solution
MainMenuUI.cs these will call the tasks from my other script
to create or join the task
and in my other script, I'm calling the Coroutine
which will execute UI stuff there
what do you think of that?
This is quite a mess, the coroutine in your first script calls an async method in the second script, and then when that method finishes it now has to start a coroutine of the first script
Okay sure, but from my understanding, your first script is where the actual logic lies, your second script is only there to handle the create/join part, and then it should hand the control back to first script.
But because you don't know how to do that, so instead the second script calls some method in the first script after it's done, effectively spliting your main logic into two scripts.
Which is my point about not mixing coroutines and tasks, if you use only one of them, the main logic will sit only in the main script, and the part that calls the second script will just await/yield it and continue. The second script will no longer need to even know the first script exists, untangling this mess.
I gave you the decision to "use only coroutines" or "use only tasks" but you still haven't decided yet.
Or I guess there's a third option, still using a mix of both.
It doesn't really matter which one you choose, but choosing one means you want to write everything in that, and not mixing them.
Unless you don't have the time to rewrite existing already mixed code, in that case you can wrap task into a coroutine (or wrap coroutine into a task, depending on the caller)
I don't know if I want to use UniTask
but I'm down to make my coroutine, a task
that way I have both tasks
Make your decision:
- I want to use tasks for everything, and I'll rewrite all my existing coroutines into tasks (you will want to use UniTask for this so your life is easier)
- I want to use coroutines for everything, and I'll rewrite all my tasks into coroutines.
- I don't have the time to rewrite and just have to mix the two.
btw the coroutine
it's just to have some delay on my UI, it looks smoother that way
btw
I have to download UniTask from github?
or I can add it through the package manager
Have you decided 1 2 or 3 yet?
all tasks
Yeah you can add UniTask via package manager, their repo README has instructions.
one sec
I'll brb in like 5-10
what I did work nicely, but I'm willing to improve my code
if this is better
I'll brb in like 10 minutes tho π¦
Can someone refresh my memory on Gameobject cloning and spawning? I was going to offload some of my code that handles creation of objects into a separate script but remembered you can only instantiate in monobehaviors
All it does is basically copy a gameobject, strip everything except for mesh renderers and filters and apply a specific material to them. Ideally it's just a helper method that takes in any gameobject and returns processed one
Would this be possible without adding a whole another component to a gameobject?
Instantiate is a static method. You can call UnityEngine.Object.Instantiate anywhere
It's the same method you're calling from doing it in a monobehaviour.
Sure seems to be working statically, tnx
For some reason I thought there was something special about monobehaviors in that regard
Bump
Maybe you can try asking in #π±οΈβinput-system instead, you may find better answers there
My project's prefabs keep getting overwritten by an older state, and I have no idea how. How do I enforce that, at a given moment, the version of the prefabs persisted in the Asset database are the ones that are present in my project?
I'm just getting my applet stood up (webgl app) and there's a lot of visual tearing and failed antialiasing in the applet (but not in editor or in windows builds). What.. do I need to explore to configure and fix this?
(look at the edges of the hexes - left image is the webgl applet)
both look equally aliased to me
left image:
right image:
one is just much lower resolution
its not really an aliasing problem, more like just seeing a completely different color through the cracks in the ground
which will naturally create those small pixel gaps due to monitors being pixel-based and objects in the world being floating-point-based
(can't speak to the tearing though, sounds like vsync issues with the engine on that platform and no clue if you can do anything about it)
sorry, I didn't mean tearing like vsync tearing, I meant the antialiasing
it's really bad on the web version.. but it might be a resolution thing .. I just noticed i'm running the editor build in 4k and the web build in 1920x1080 from the canvas size
I'm not really sure what the appropriate method is - like.. size the canvas with javascript to the browser size?
I'm hunting around for a good webgl template but i'm pretty bad with web stuff
Quick question, is there a common reason windowed mode would not include a windows bar at the top of the application? Every time it launches, the bar is there but then after the splash screen it disappears
I would like the bar to be there, is there a way to force it? I've tried declaring the fullscreen mode in script, even using a couroutine and key shortcuts to do it manually, and nothing I've attempted has worked. Am I just missing something?
can you screenshot of how the top of your windowed mode looks like?
just to make it clear that we're thinking the same thing
How do i learn things? Im gettting to a point where I dont know what I dont know how do I learn things? Also whats the best way (or a good way) to refrence a component on a prefab in a script on the same prefab
make
[SerializeField]
private MyComponent _component;
in the script
and assign it from inspector
when you want to make a new feature but arent sure how to implement it, then worry about learning more things. Or even just google to see how others implement it. Maybe you'll find new components or c# features you werent aware of. if you are a beginner, you'll quickly come across many new things
and also dont crosspost #πβcode-of-conduct i just saw you posted in the beginner channel after answering.
you dont reach a different part of the community by posting in both channels. its just an annoyance to those who look at both
I have a question, when using Input.GetButtonDown does it always have to be in the update method ?
It needs to be somewhere that runs every frame
Update, LateUpdate, a coroutine that has a loop that runs every frame, or something called from one of those places.
ok, I thought so but figured maybe there might be another way.
the other way would be the new input system, more of an events style for input
That's more of what I was looking for, I'd imagine the overhead however small it might be would be better, but then again maybe the new event system is using the same update code something similar to detect.
the performance of this stuff basically shouldnt even be considered
How do I change the "Color Over Lifetime" property of a Particle System at runtime? This doesnt seem to change anything, ive also tried changing col.color.gradient directly without the g variable and looping colorKeys to change it, am I missing something?
for (int i = 0; i < vfx.Length; i++)
{
var col = vfx[i].colorOverLifetime;
var g = col.color.gradient; g.colorKeys[0].color = g.colorKeys[1].color = tone;
col.color = g;
}
vfx[i].colorOverLifetime = col;
Thats the strange thing with the particle system, you cant assign those properties directly, for example
var main = vfx[i].main; main.startColor = tone;
is all thats needed to set the start color, but doesnt seem to be the same for color over lifetime, if I try vfx[i].main.startColor = anything I get a read-only error, same with vfx[i].colorOverLifetime = anything, same for any of the sub properties like vfx[i].colorOverLifetime.color = ...
Now im really confused, creating a new GradientColorKey[] and passing that seems to work, but why would I absolutely have to create a new struct for this? Why cant I just change one value of the existing struct? Doing it this way means if I have 5 color keys, id have to make a new array, loop through all 5 just to change 1 then pass that whole new array, instead of just change the 1 index directly, is this the only way?
I've got a shader that I want to use to give a 2d sprite a semi-white overlay when the mouse is hovered over
The shader will turn my sprite green, red, any other color
but when I tell it to turn it White, it does nothing
What am I doing wrong?
why not?
detect if your player is trying to climb steps. do the raycast. teleport him to the new position if it succeeds.
theres probably some other checks you'll need to do, but that's basically the gist of it
you should probably draw lines as well to make sure your raycasts are happening in the right spot
I ended up getting the script to work
why do i get this error:
IndexOutOfRangeException: Index was outside the bounds of the array.
UnityEditor.Editor.get_target () (at <c84e7af800564ed28d201f1f7edf8e24>:0)
WallManagerEditor.OnEnable () (at Assets/Scripts/Walls/Editor/Wall Manager Editor.cs:43)
that is this line of :
private void OnEnable()
{
_asset = target as WallManager;
}```
i don't see why that would be an error ive made plenty editor scripts in my time and i've never had this issue before.
im going to assume it must be an engine bug not something i've done since i dont have access to get_target
What is target?
Are you doing some weird multi target selection event from the inspector?
no i only have one scriptable object of it
What is _asset?
I'm ensuring it isn't some sort of indexer overload
class variable WallManager _asset;
Does it throw an error if you simply log _asset or target?
Reducing the complexity by removing the assignment and cast from the equation.
no they both print WallManager
the editor seems to work even with the error popping up
So if you do not execute that statement and simply log the two there are no errors? (not caring if it works or not, simply if there is an error being thrown or not) cs private void OnEnable() { Debug.Log($"asset: {_asset}"); Debug.Log($"target : {target}"); Debug.Log($"target as WallManager : {target as WallManager}"); //_asset = target as WallManager; }
it seems to all show wall manager correctly even for _asset when it should technically be null v.odd
let me restart unity maybe something has gotten stuck
ah restarting fixed it
how odd
something funky must've gone on when recompiling after editing a script
anyone know if there are plans (or maybe already implementations, in Unity 6) for C# 12 features? or are they just not bothering with backporting features now since they're working on porting everything to CoreCLR/.NET 8 anyways?
not that there's anything in particular i need, just curious
I have a placing script that uses a raycast to find a spot to place the object, the problem with this is that where it WILL go is sometimes inside the wall or something (like in the image, the red is me holding down my place button), how do i make it have an offset or something?
What kind of offset? I'm unaware of what's wrong with the picture. You'd probably want to show what you've tried so others can add-on or suggest fixes to what you've got.
The red card is a clone of the yellow card, so currently it is clipping into my desk, I need it to not clip into the desk
Where should it be instead? On top of the desk, on the floor or?
It should be in front of the cupboard, it is half in the cupboard right now
Take the normal of the raycast and offset it by that direction relative to the size of the block.
What if the size changes? Like if I have a different object I want to place
You should be able to figure out the size at realtime
depending on the variety of objects you have and what kind of other areas you might use them in, it may (or may not) be better to just offset the object's origin itself (either in your modeling program or using an empty gameobject/prefab)
but what dalphat mentioned is the solution otherwise, just depends on what you have going on
No idea which channel could be for that, however
I've got a class ClassA and ClassB, the latter taking ClassA for a variable. I've got multiple ClassAs attached to a gameObject, and need to assign a specific one to ClassB in another gameObject, hoepfully through editor.
// Some visualisation of the code
public class ClassA : MonoBehaviour {...}
public class ClassB: MonoBehavior
{
public ClassA classA;
}
Is that even possible, if so, then how?
both are scene objects?
Yes
open 2 inspector tabs, lock one to the from object, select the to object, drag and drop the correct classa
Ohhh, that'll work. Thanks π
Yeah that won't work because it can be any rotation
I'll give it a look
it'd work, you'd just need to rotate the object according to the raycast hit's normal (probably using Transform.LookAt but it depends on your object)
you'll have to do that with either method, more or less - since with dalphat's method you'll need to know which direction to actually offset the object toward, otherwise it'll just go half its size into the surface, probably at the wrong orientation, unless you've already figured that part out
(if you want it to be flush with the surface it hits, which I assume you do)
I also have a rotate feature where when placing you use the scroll wheel to rotate it around, there was a suggestion to get the gameobjects box collider and then offset that somehow
you shouldn't need to do anything with the collider (unless you're trying to ensure valid placement or something, so that it isn't intersecting with anything). the raycast hit's normal should be be enough, as long as the normals on your mesh aren't a mess i think
(at least for the rotation part)
if you do try to validate the placement with the collision you'll probably need to offset the placement a tiny bit so they aren't fully touching, or use some method to check how much of the mesh is intersecting with the other one i guess
Any ideas how to get the cell the mouse is touching in a 2d isometric tilemap, that has been rotated to 35.264,45,0 to match a 3d cameras isometric perspective?
Hey I'm calling Destroy on an object when I click on it but when that happen i get the following error: (image)
My issue is that the error itself doesn't seem to come from my code but from the EventSystems
I'm calling Destroy that way:
public void TryGiveBurger()
{
// Update health
if (_health <= 0f)
{
OnDeath();
}
}
protected override void OnDeath()
{
CustomerManager.Instance.UnregisterCustomer(gameObject);
Destroy(gameObject);
}
Would anyone please know how I can fix that?
Yeah this can happen if you destroy the object that the event system currently has selected
or is otherwise processing somehow
It might help if you do. something like deselect that object before destroying it and/or delay destroying it until the next frame.
I tried to delay it to the next frame, I think it kinda worked for a bit but somehow the error is back?
Also I tried this EventSystem.current.SetSelectedGameObject(null); but it doesn't do anything
My old code was
protected override void OnDeath()
{
CustomerManager.Instance.UnregisterCustomer(gameObject);
StartCoroutine(Delete());
}
private IEnumerator Delete()
{
yield return new WaitForEndOfFrame();
Destroy(gameObject);
}
Yield return null is the way to wait one frame
But I might be mistaken about deselecting it being the problem, it might just be because you had moused over it.
hmm i still have the same error
Making it block Raycast = false might work better
Or Raycast target
Forget what it's called
I'm trying that
Yup I added GetComponent<Image>().raycastTarget = false; and it works, thanks a lot!
Nice
Hey it's me again, so apparently it fixes the issue in Unity editor but I made a build and sent it to someone and the error pop up again
I am developing an inventory system for an MMORPG and would like to dynamically create objects, even if there are no pre-created ScriptableObjects. I plan to use both random parameters and base parameters for these objects. Additionally, I need the objects to be able to be created on a server request or purchased in a store, with the ability to assign items received from the server. Is this even possible? What efforts and approaches will be required to implement this system? I am considering the possibility of using reflection and flexible OOP approaches.
I would appreciate any advice and ideas!
Everything is possible obviously but what you're describing is a complicated system with many moving parts. I would avoid reflection.
Split up your problem into steps. The networking aspect is a completely different problem from dynamically creating objects. Though it doesnt really make sense what you mean by "even if there are no pre-created scriptableobjects". Why use scriptable objects if you dont plan on just creating these in inspector? That's the whole point of them
hello, what I'm doing wrong? When Im moving slider to zero, db goes back to middle
Are you following a tutorial? The tutorials should tell you to limit the slider to 0.001 or something because Log 0 is undefined
my dumbass made a whole script that renders a linerender with the same points as a polygon collider to be able to rotate a laser
instead of a simple sprite + raycast
it took 2 HOURS
at least it has width
I wasn't but I was sure its something about math. Thank you!
I have a method that instantiates and fires a bullet every second. In the middle of gameplay, the firerate can be changed by getting upgrades. Its not clear to me how to best get the method to take and use the new fire rate value. Currently I am doing a bit of work around by making a public method of the same name and having it call the private firerate method with ref inputs
do you have a script that stores the upgrades?
the best way would be to make the firerate(of the gun) public, and changing it in the upgrades script when the player gets an upgrade
Some other approaches that come to mind is using a event in your weapon script, your upgrade menu can fire it if it has a reference to your weapon already, or use a broadcaster/global event if not - or you could make a public property that can be changed and add/subtract it from your fire rate, this way your original firerate can remain private and only affected by the class it exists in, while still accepting modifiers that can also be removed later or possibly saved
nice approach, but if they are unfamiliar with events,they could just make a separate variable that is public and can be accessed by the upgrade script, and keeping the original private then doing the modifications
I don't think it is necessary to keep the firerate private
This is actually similar to what a public property would do, it acts as a variable but it can also act like a paramless function and do some validation, for example maybe fire rate should never be 10 million
The main reason youd want a variable a class uses like firerate to be private, is cause only that class actually uses the value, everything else might just want to see it, but not modify it directly, when you allow that, then literally any script in your project can modify it at any time, and if thats happening from multiple places, it can be difficult to debug, or run into race conditions where 2 classes are fighting to change the value
Np
Are you supposed to create transforms from position and rotation in order to use point transformations? If I wanna transform a point to local space (location+rotation) but it isn't tied to an existing gameobject, what's the best approach?
if you don't have a transform, then what "local space" is this supposed to be converted to?
I'm blabbering let me rephrase it more coherently
I have a point and I need to offset it by some position vector and rotate by some quaternion
I could do it separately but I'm pretty sure that's what TransformDirection does anyway. Is there any way to do it in one go?
you can rotate a direction vector by multiplying it by a Quaternion representing the amount of rotation so just do that and add the offset
I'm doing it rn but it was kinda a hassle to provide both location and rotation for 2 objects in a function, was wondering whether there's some transform data type that combines both of these
And maybe scale too
Like a general purpose transform matrix or something
theres this if this is anything to you
https://docs.unity3d.com/ScriptReference/Transform.SetPositionAndRotation.html
Because iirc transform component also handles things like inheritance, children etc
Nah I just need to transform a vector
afaik there is nothing like that built in. but it sounds like you know exactly what you want and the transformations you would like to do and how to do them manually, so just make one yourself
Yeah it won't be super hard to just make a custom one I just wanted to make sure I'm not reinventing anything
Ty
The first steps might be wrong, what do you think? I'm not an expert, just trying to break through the ceiling ;))
https://hatebin.com/fefdjoqspg
https://hatebin.com/puohfqcquz
Hey crew. I'm getting a Unity error NullReferenceException: Object reference not set to an instance of an object UnityEditor.Android.AndroidDeploymentTargetsExtension.StartApplication however the APK is uploaded to my device and I can start it successfully. I tried all the solutions I found online but none of those applied to my situation. Anyone seen this before?
this is probably the most common runtime error. look at the complete stack trace
messing around with a little voxel project, and i'm not sure how i can fix my normals. each voxel is part of the one gameobject, created through vertex/triangle manipulation. currently, the individual cubes have the same shading as the whole object should combined. not looking for code, just a list of things to look into, any help would be much appreciated <3
Is there anyway to use C#10+ (a version above C#9) with Unity ?
have you googled it? also you will only get the syntax sugar features from c# 10, you won't be able to use anything that is not supported by unity's .net version
I've tried to Google, only thing I could find are instructions in Cysharp/ZLogger#unity, but I don't think it works for local projects (well, I couldn't make it work)
Does flat namespaces count as sugar?
no
flat namespaces?
file scoped namespaces
You would also need to manually patch the compiler binary in your Unity editor installation
Not really worth the effort imo.
There is a tutorial on YouTube (HERE) that might be beneficial to what you are asking
JOIN THE DISCORD SERVER!
NOTE: I have NO idea what happened around the 6:30 minute mark with the epilepsy-inducing flashing red screen. Sorry about that :-/
This is my first attempt at a coding tutorial video. As I explain in the vi...
It is a series so there will be textures in later videos on it
tryin to avoid tutorials, hence the not wanting code thing, i find i don't learn anything if i use a tutorial, sry to be a pain
I found this tutorial very helpful when following it a while back, it might give you some insight on how to better your code, other than that i'm not sure
Can anybody recommend a method of applying and deactivating redundant status effects when effects are applied with a component pattern? For example, suppose I have a state in which a character is made to be drunk for a period of time. What I've seen in the pattern is the following:
public class Drink: Effect {
private IGetsDrunk Drinker;
private int timer = 60;
public void Activate(Target t) {
if (IGetsDrunk _drinker) {
Drinker = drinker;
Drinker.Drunk = true;
}
}
public void Deactivate() {
Drinker.Drunk = false;
}
public void FixedUpdate() {timer--;}
}
This solution is pretty nice to me, because the state update is calculated once, and the only calculation to do for the rest of the lifespan is decrease the timer and undo the effect when it's done. This doesn't seem to work if the effect is applied redundantly. For example, if the character drinks a drink at t=0, they can expect to be sober at t=60. If they drink again at t=55, they'd expect to be sober at t=115 (let's say), but the above implementation would make them still sober at t=60. Is there a clean way to account for this in a component pattern?
I'm trying to get what the camera sees (the first image) to map onto a raw image in a canvas (the second image) but doing so causes the second image to be stretched out and kind of low res. How do I fix this?
Hi I'm trying to make an animation script. I made the clip. I'm familier with python but not so much C#. I have 2 characters talking to each other with dialogue (text file containing each line of dialogue). The audio comes through, but I need the characters' jaw to be open while it's their turn to speak, and close when not supposed to be speaking. I wrote this script here, Unity found no errors, but will it do what I actually want it to do?
speaker should match the name of the character object
startis never going to be called, as it's not capitalized how Unity will expect.- I have no idea where you call
ProcessScript - Your
File.ReadAllLineswon't work in a build, and will only work in the editor because the file system is completely different when built (Assets doesn't exist). - Do you have error highlighting in VS Code? While it looks highlighted, I'm suspicious it's unconfigured
I did take part of this from someone else's code
That's in Main.cs whcih controls the whole thing
But it didn't actually do anything
Also this is invalid:
Yeah I'm just throwing stuff at the wall to see what sticks π
I did do C# research but perhaps not enough
well, read and understand the dot points I've mentioned for a start
if your IDE isn't configured (4) then that's a major thing you need to set up asap
It might not be configured
!vscode
How would I create an inputmanager for keybinds?
I'm thinking something like this:
public InputManager instance;
public List<keyBind> keyBinds;
private void Awake(){
if(instance == null)
instance = this;
else
Destroy(gameObject);
}
[System.Serializable]
public struct keyBind
{
public string name;
public KeyCode key;
public KeyCode altKey;
}
And then in my player script it would look like:
if(InputManager.instance.keyBinds[0].key || InputManager.instance.keyBinds[0].altKey){
// Jump code
}
Looks fine. Although, maybe use a dictionary instead of a list.
What would this look like in a dictionary?
Same as in a list. Just in a dictionary. Use a string or an enum for the key to identify the input and your struct for the value.
Why would a dictionary be better?
It would be faster to get the value compared to a list. Though, if you just indexes as in your example, a list would be around as fast. But then you have an issue of poorly readable code, where you hardcode the indices.
How do I access items in the dictionary? I haven't really used dictionaries
Hey all, is there any tutorials around that go through how to implement text chats with vivox's current version? the documentation is pretty sparse
Same as lists/arrays. Except that you use a key instead of an index
Check the C# docs.
So I'm making a rope with IKs, but I'm trying to add gravity. Heres my current idea:
Calculate the ik as normal, then I'll find the middle segment, and move it down. after that, i'll calculate the other to halves back from the center with the anchor thing. I'm trying to figure out how to code it, but I'm wondering if anyone has any other ideas.
I move a pool of objects each fixed update, but since they are marshalled, it ends up with some performance loss. Is there a workaround to keep the transform in memory?
should I just store it as a variable, is it fine?
how many vertices do you have per cube? 8 or 24?
Currently i've got this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour
{
[SerializeField]
public Dictionary<string, keyBind> _keyBinds = new Dictionary<string, keyBind>();
//public List<keyBind> keyBinds;
private void Start()
{
keyBind k = new keyBind();
k.key = KeyCode.W;
k.Altkey = KeyCode.UpArrow;
_keyBinds.Add("Forward", k);
}
[System.Serializable]
public struct keyBind
{
public string name;
public KeyCode key;
public KeyCode Altkey;
}
}
Depends on the cube. You can even have more.
I guess, just wanted to make sure they don't use a mesh with no way to shade flat which is quite likely here
You could shade it flat with a custom shader probably
Even with just 8 vertices
It is possible with partial derivatives of the position for example but I think they still usually use 24. Some also do that to split the chunks into different directions to cull the ones pointing away from the camera
also if greedy meshing is implemented, the vertice count increase isn't that big of a deal
Not sure what greedy meshing is, but I was just answering your question: you can have a cube with just 8 vertices.
You can but I just wanted to point out that often times people split the edges to make things easier. One thing that I forgot is UVs which may cause a lot of headache if the edges are not split
Again you can work around that too
I've been stuck on this for hours but how would you go about creating a rope that player can climb and swing on which uses physics. For a 2d project btw
look into joints
Making the ropes isn't the problem .
The ability to latch onto it and generate momentum and climb is
That's what you asked...
Also using joints, and AddForce
How am i going to get the input? i've got the keys setup, how I do like if(Input.GetKey(Key))
Input.GetKey(keyDictionary[keyKey])
And then there is Input.GetAxisRaw("Horizontal"); would i just use
float horizontal = 0;
if(Input.GetKey(keyDictionary[left]) {
horizontal = 1;
}
This seems pretty unnecessary. Have you tried the new input system? Itll be miles better than this
I have not no, but it seems that the input system that i'm using currently is working
I generate a mesh for my voxel grid, and I make sure to never repeat vertices. However, this makes the lighting off, as the vertices never repeat and so, faces reuse older vertices. This makes the faces render in a similar fashion to balls, which could look nice if the voxels were very small, but it looks off when the camera is close to the voxels.
How can I fix this issue?
Make sure the triangles are using the correct vertices. Also make sure you recalculate normals after creating the mesh.
All triangles are using the correct vertices, and I do recalculate normals.
Well, the screenshot points out otherwise.
This doesn't really prove anything.
You wouldn't see here whether the triangles share vertices or not.
They do share vertices because I wrote the mesh generation myself so I know what it does. I basically create a list of each face that would be visible (no voxel is occluding it), and then when I cut the face into vertices and triangles, I check if the vertice is unique or not. If its not unique, I use the index of the vertice that already exists in that position.
Well, that's the issue
Is there a way to keep the same optimization while having the normals correct? I know the normals look like the voxels are balls due to the vertice sharing.
Your triangles need not to share vertices to get flat shading.
A vertex can only have 1 normal.
You can patch this in a custom shader by calculating the normals for each pixel, but that would be even more expensive
;(
I used a similar optimization in a voxel engine I made outside of Unity a while ago and I remember using screen-space normals there too.. I suppose there's no way out of that then?
There isn't. And screen space normals are probably gonna be way more expensive than some extra vertices.
I guess I'll just keep the vertice unique thing in the trash bin until I find some way to make it useful
Thanks!
And to be honest, if you're aiming for a performant engine that can render a huge amount of voxels, unity is probably not a great choice.
Not really aiming for that in this project. I just like making my stuff very performant.
Thanks for the help. Next I plan to implement greedy meshing to reduce vertice count.
unity's fine for this kind of thing too, you'll just need to use some of the more low level APIs imo!
you could use ddx/ddy on interpolated world space positions to pick normals, I don't think it'd be too expensive!
Still very new to using custom shaders in Unity. How do I create one ;(
oh, hm, which render pipeline are you on?
if it's URP/HDRP then you'll prolly want to use shadergraph
rn I'm on the default one but if I can use ShaderGraph for this sort of thing then I should probably use it before trying to delve straight into anything too complex
I forget if SG has support for the built in RP
(I mostly write shaders in the built in RP)
I believe ShaderGraph should support the built in RP as it doesn't say its for URP but says URP provides support for it
but a quick google search says otherwise
so I guess not
I think it was added in 2021.2?
anyway, you'll want to do something like this:
outputNormal = normalize( cross( ddx(worldPos), ddy(worldPos) ) );
assuming the outputNormal is in world space, it might not be
How do I create a shader in the built in RP? I want to check if it'd be comfortable or not before going with Shader Graph
do you want to support lighting?
if so then SG is going to make life a lot easier
(unity has kind of started discouraging writing shaders by hand through their design ever since shader graph)
(writing shaders by hand has a ton of drawbacks if you want to support all the features like lighting, motion vectors, scene view selection, all that. but you get a lot of control!)
basically using SG is more future proof lol
I suppose I don't really need a ton of control for this project anyway, so SG should work.
but yeah right click in project view, Create > Shader >, and then Unlit is writing by hand. shader graph should be similar but I forget, I rarely use it 
might need a package or something
Greedy meshing not going very well at the moment ;-;
Can someone more experienced explain to me why my algorithm doesn't work? I basically have a list of every voxel face (that is going to be rendered), and I group the faces if they have the same normal. Afterwards, I iterate over them and check which ones align along the X or Y axes, and merge them if they do.
I also check if the distance between them is too much
I think I should try to rewrite it fully since this approach is probably wrong
Hi again everyone!
I have a "skill tree" with each skill its script (ItemSkill). The gameobject of the skill contains also the panel that will show when clicked that allow you to upgrade to the next level, and this is for every skill. Since the "price" for the next level will always be the same the initialization of the upgrade panel is made only once at the start.
Wouldnt be better to unlink the upgrade panel from the skills and initialize the panel every time i click on the skills? (so before if i have 10 skills i have 10 panels, now i have 10 skills and one panel)
is this how I should make that?
I'm guessing not exactly since it looks weird
using view space instead of world space makes it look a little better but its still weird
oh, the output node says tangent space
there might be a setting to change the output normal space
if so, change it to world
8, not sure how 24 would work
generally you'll need 3 vertices per corner of a cube if you want it to have hard edges in terms of shading, since there's only one normal direction per vertex
(there are ways to work around it but that requires specialized shaders)
not a code question #π±βmobile
i'll move it, cheers
Its black now
uuuh did it get disabled somehow
idk
yeah that looks disabled
The way I changed it to a world space normal is by deleting that part and then replacing it with the world space normal
