#archived-code-general
1 messages · Page 357 of 1
It sounds like you might have had some exposure to the callstack
i kind of skipped from C# straight to assembly for a little
and then did some stuff building circuits and RAM and such (in minecraft, i can't afford to build real life ones lol)
@leaden ice thanks for the help seems to be working fine!
how do I check if this thing is on or off?
yo guys any tutorials and documentations on how to code 3rd person camera without cinnemachine
@swift falcon Don't cross-post, please.
mb
SteamFriends.ActivateGameOverlayInviteDialog((CSteamID)current_lobbyID);
I currently have this to open the invite menu, but it just opens steam overlay with a list of friends, how do I get the menu where you have those "invite" buttons?
I have an system where players can pick up dropped weapons by pressing F. But when the player picks it up, the weapon doesn't go to the hands transform but rather above their head. The weapon is still a child of the hands transform upon pickup. The hands transform works indicated by the rocket launcher. The pistol and the knife doesn't apply
Here's all the code associated:
https://hastebin.com/share/ibiqahohih.csharp
https://hastebin.com/share/kazamawofe.csharp
I would check the pivot of your hand transform and the pivot of your weapons, you should also make sure you are zeroing the local position of your weapons after parenting it, if all your weapons have different origins, they will be positioned differently once they are a child, you could give each weapon its own parent and move the base of the weapon (the part the hand should cover) to the origin of that parent, this way when you set a weapon as a child and zero the local position, it will be on the parent that contains the specific weapon positioned where you would like
i have this gameController structure i want to pass into this script. but i cant drag and drop it in there. I assume its because there are children attached? Are there any workarounds?
public class TileClick : MonoBehaviour, IPointerClickHandler
{
public GameObject gameController;
public void OnPointerClick(PointerEventData eventData)
{
gameController.GetComponent<GameController>().clickTile(transform.position);
}
}```
if i try and select it from the available objects it says there is a type mismatch but i dont understand why
you cannot set a scene object onto a script, only an instance of the script attached to a gameobject in the same scene
so i have to create an instance of GameController?
that you already have, you need to attach this script to a game object and assign there
i attached it to an object, but it doesnt let me drag and drop the GameController object in the object field
show the inspector
that is a prefab not a scene object
ah
do i have to make a GameController prefab then?
no
do i assign the function/object when making a new tile instnce?
Most likely want to assign the scene references when you instantiate the prefab.
yes
how do i do that?
i already have a script attached to the tile, in the start function, how to i get the GameController object?
after instantiating the prefab get a reference to the TileClick script and set the reference to the GameController
you should hold a reference to it in the script that instantiates the prefab
The tiles are instanciated by the tile handler script, do i put the reference in there?
ah ok
if GameController is a singleton it's even easier
i got it working, thanks!
I am a beginner in unity requesting some support
Can someone guide me on How to make a search dropdown and then use the selected option as a variable input into a script
Kinda like the search bar on top of google maps ui
alright so not sure if this would fall under animation or coding, but I'm trying to get my characters attacks to actually deal damage. I've only dealt with platformer movement, but this new project I'm working on has 4 directional top down movement, and I genuinely have no idea how to get my character to attack. I've looked up multiple tutorials, but I just can't seem to find something that works with my character
for reference the asset package I'm using doesn't have a visible "weapon" and most tutorials require an attack point object to be created on attack
Well, there are several main methods:
- deal damage on actual physical hit, when your weapon hits the target.
- deal damage at certain timing(like at certain point of animation), regardless of whether the weapon physically hits the target.
There are also more complex approaches that are a combination of the two.
You should decide what kind of approach you want to follow first.
Since my character sprite doesn't have a weapon attached to it, I think the second option would work a lot better. Especially considering the attack has 4 seperate animations for each direction
for example this is what my character sprite looks like
this is quite easy to do (code wise)
the only annoyance would be getting a dropdown-like window under an InputField (aligning UI
)
bumping this, deltaTime indicates we're not on a timescale of 0, is there something else i should be aware of that might be causing problems?
typeof(Object).IsValueType
You can actually use reflection to check for almost anything, templates, generic types, unmanaged, etc
For value types, if you create one in a function it's on the stack. If you have a reference type holding one, instead of a seperate memory block and a pointer to it, it literately holds all the values inline
ie. If I had a class A which holds an instance of class B, where sizeof(B) is 24 bytes, sizeof(A) is 8. But if class A holds an instance of struct B with the same size, sizeof(A) is 24.
Should avoid reflection in unity, causes extra gc overhead and is slow
maybe they mean for just testing
maybe. But i dont think typeof and sizeof is really going to affect it, i think its mostly the stuff in System.Reflection
Is typeof reflection? I thought that was compile-time shtuff 👀
i think typeof is compile-time and GetType is reflection
i'm having a weird issue where using Camera.WorldToViewportPoint returns different results for the same position, could something like SRP be the cause?
Whew. Good. I just wrote a small pile of code leveraging it 😅
the difference between the two would probably be insignificant in performance anyway
Oh I'm sure you're right. Especially in such small quantities as what I'm doing. The thought that I unwittingly may have stumbled into reflection was just a bit of a spook
for reference, running from the same input position and camera i get these results
Can you share the relevant code?
yeah, give me a second, gathering everything rn
Well, technically, i think typeof is reflection but just known at compile time.
oh wait, i found the issue. camera wasn't in the same position
what's the standard method for handling different bullet impact effects based on the materials of an object?
my initial thought was using CompareTag but I have stuff that needs tags for other gameplay reasons
Put a component on the surface that has details about it including what kind of impat effect
yes presumably you're using OnCollisionEnter or a raycast or something, you just TryGetComponent to find the "surface material" script and do what you need to do
Yeah I'm just saying for testing whether it's a value type
why do you need to test if its a value type?
i dont need to i just want to know how to
ohh okay
My game world has ~10,000 objects, and I only want the objects in a specific range of the player to be visible. However, the objects refuse to be enabled when they enter my sphere collider. Here's the code to turn them off at launch:
private bool init = true;
// Attached to objects
void Start()
{
if(init)
{
gameObject.SetActive(false);
Debug.Log("Outside Render Distance!");
init = false;
}
}
Here is the code for the sphere collider:
void OnTriggerEnter(Collider other)
{
if(other.tag == "Decoration")
{
Debug.Log("Spawning Object");
other.gameObject.SetActive(true);
Debug.Log(other.gameObject.activeSelf);
}
}
void OnTriggerExit(Collider other)
{
if(other.tag == "Decoration")
{
Debug.Log("Despawning Object");
other.gameObject.SetActive(false);
Debug.Log(other.gameObject.activeSelf);
}
}
This feels like this should be simple, but I just can't wrap my head around this. Any assistance would be appreciated.
well first of all, unity already has built in frustum culling so anything not in the camera's view frustum will already not be visible. second, occlusion culling is also a thing so you can cull even more objects that are occluded by other objects so you don't need these trigger messages for stuff like manual culling
and if trigger messages aren't working then you need to use this to evaluate why: https://unity.huh.how/physics-messages
I don't believe this will help in my case. The game environment is a procedurally generated planet, and the objects placed on it are also procedurally generated. Because the planet itself moves, occlusion culling won't work. For the debug messages, the objects that are initially within the sphere collider report a collision, and activeSelf is true.
well frustum culling already exists and works with proc gen stuff, and the camera's clipping far plane can be used to not render objects beyond a certain distance, so unless you are doing anything special in OnEnable/OnDisable or you need specific components to not update when those objects are out of range, what you are doing is mostly pointless
Um are the objects disabled? Cus it won’t send the messages if they’re disabled.
that would be one of the things covered in the link i sent regarding physics messages
Running into an issue, where I'm just trying to get some simple background music to play. I start up the game, but it doesn't go. Anyone have any thoughts as to why?
using UnityEngine;
public class AudioManager : MonoBehaviour
{
//Set up a variable for playing music. I'm setting them up to be separate, music and sfx.
[SerializeField] AudioSource musicSource;
[SerializeField] AudioSource sfxSource;
//Now we'll create a variable to keep the music and sound effects in an AudioClip.
public AudioClip background;
public AudioClip jump;
public AudioClip winLevel;
//This function will set up the background music to play when the game starts.
private void Start()
{
musicSource.clip = background;
musicSource.Play();
}
}
any errors in the console? have you confirmed that the clip is set on the correct audio source and that the audio source is active and enabled?
also have you ensured that the editor isn't simply muted?
and you dont have audio muted in the editor
Oh, it's saying there's no audio listeners in the scene? I'm not sure what that means.
your camera does not have an AudioListener component. which means you either have no camera, you manually removed the AudioListener from the camera, or you just added a camera component to some object manually
Gotcha! So, what should I do if I want the music to continue to play to the next level? Since it only plays for that level, and then stops once it loads the next level.
you need to make your AudioManager and the Sources DDOL
DDOL?
Dont Destroy On Load
Ah, gotcha.
Running into this error. Trying to set up this script so when the character goes hits the trigger, it plays.
public class FinishLevel : MonoBehaviour
{
[SerializeField]GameObject victoryTextObject;
[SerializeField] float levelLoadDelay = 5f;
[SerializeField] string levelToLoadName;
//Reference into audio manager script.
AudioManager audioManager;
//Setting up sound stuff here.
private void Awake()
{
//Setting up the sound effect here.
audioManager = GameObject.FindGameObjectsWithTag("Audio").GetComponent<AudioManager>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
//Taking advantage of player tag here for collission stuff.
if(collision.gameObject.CompareTag("Player"))
{
StartCoroutine(LoadNextLevel(levelToLoadName));
}
}
IEnumerator LoadNextLevel(string newLevel)
{
//Enable victory text.
victoryTextObject.SetActive(true);
//Play sound effect.
audioManager.PlaySFX(audioManager.winLevel);
//Wait for levelloadDelay number of seconds.
yield return new WaitForSeconds(levelLoadDelay);
//Load new level here.
SceneManager.LoadScene(levelToLoadName);
}
}
any one know why triangle is disappearing?
For now, I've turned off the initial despawning script. The objects now despawn correctly when the sphere moves away from the object, but it should appear when the sphere moves back, but it doesn't.
yes because OnTriggerEnter won't be called on a disabled collider
so again, what you are attempting to do is pointless
GameObject.FindGameObjectsWithTag("Audio")
returns an array of GameObjects. Arrays don't have a GetComponent() method
Is this AI code?
objects returns an array
smells like AI code
..actually I dont even think AI code would fuck this one up tbh
That's not what I'm reading from the documentation. Every entry regarding collision triggers say that they can trigger on disabled objects.
no, it says it will call OnTriggerEnter on disabled MonoBehaviours, but the colliders still need to be active
which means the gameobject must be active
I was following a tutorial, but I think I should be using FindWithTag instead?
So I need to disable just the mesh renderer instead of the entire gameobject? Let me try that and I'll report back.
you should be reading the docs
i mean sure, but again frustum culling already takes care of this for you
you are not saving any performance by doing this manually
The objects are spawning and despawning as intended. The issue is that the colliders are still loaded, causing performance issues. Also, since every object is dynamic, fustrum culling won't work.
wdym frustum culling won't work? frustum culling will cull anything not currently visible by the camera within the camera's view frustum
and if colliders being enabled is causing performance issues, then using trigger messages to enable/disable those colliders won't exactly work because a disabled collider wouldn't have trigger messages called on it
I managed to get my culling script working. I switched from a collision sphere to comparing Vector3.Distance. It works flawlessly with good FPS now.
Guys, does anyone know any sane way of enabling nullability per asmdef, that would work in both IDE and Unity?
I know I could turn it on in csc.rsp, but that's for the whole project, I just want to turn it on for specific core projects that are more pure c#
cant you do that inside the asmdef file already?
I'm stil fuzzy on asmdefs
google says something about
"additionalCompilerArguments": [
"-nullable:enable"```
Thanks mate
I think both of these would work on the entire Unity project, not specific asmdefs
For example, Asmdefs have a nice checkbox for "Allow unsafe code" but nothing similar for nullabiity
Basically it would be ideal if I could plug in "additionalCompilerArguments" into asmdef somehow
Maybe this Build.Props thing can be customized
oh for the inspector ? yeah tats beyond my skill level 😛
I just hoped Unity has something inbuilt I am not aware of, there is probably some painful way to hack it
im having issues making this empty game object collide with other objects. i have some tiles which the object passes trough if i have isTrigger set to true in the collider settings, but can detect the collision via script. however if i set isTrigger to false, it collides with the tile and doesnt get detected by the script
these are the settings for the tile
well are you using OnCollision method?
also how do you move the rigidbody
oh nvm I see its a kinematic on this empty
OnTriggerEnter(Collider other)
oh im using this
you need OnCollisionEnter if its not trigger
check here though
https://unity.huh.how/physics-messages/collision-matrix-3d
collisions are very tricky with kinematic
you need the other to be at least dynamic for OnCollision to work
private void OnCollisionEnter(Collision other)
{
Debug.Log("clic");
if (other.gameObject.tag == "tile")
{
Debug.Log("Colliding with tile");
}
}```
`other` in this case is still a game object right?
https://docs.unity3d.com/ScriptReference/Collision.html
the type is right there, its a collision
got it, thanks
Could someone point me in the right direction to set up handling player turns?
setup an array
scroll through indexes
Thank you thats what I needed. I was overthinking it
Thanks!
I have a (hopefully) quick question. Is there a way to set a UI horizontal layout 200 pixels away from the scene/camera border at this resolution?
Moved to #🏃┃animation 🙂
gotcha
Can someone help me understand materials rq. When are they coppied? I need to make sure I don't get a memory leak (I think that can happen with CoreUtils.CreateEngineMaterial)
So I create a material in object A and pass it to object B through a method, where it stores the material locally to object B. If object A destroys that material, object B's reference will go null because it points to the same material right?
Yes, materials are referencetypes
when are they copied/new instances made?
iirc when you modify the materials properties
Just trying to make an instance of an object moving back and forth between two points, but the gameObject in question keeps going off to the right. Not sure what to do to fix it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyPatrol : MonoBehaviour
{
//Creating to the points where the enemy will patrol.
public GameObject pointA;
public GameObject pointB;
//Rigid body for moving the body.
private Rigidbody2D rb;
private Transform currentPoint;
public float speed;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
currentPoint = pointB.transform;
}
// Update is called once per frame
void Update()
{
//We're going to set it so the object goes between point a and b, and then reversing it once it hits the right point.
Vector2 point = currentPoint.position = transform.position;
if(currentPoint == pointB.transform)
{
rb.velocity = new Vector2(speed, 0);
}
else
{
rb.velocity = new Vector2(-speed, 0);
}
if(Vector2.Distance(transform.position, currentPoint.position) < 0.5f && currentPoint == pointB.transform)
{
currentPoint = pointA.transform;
}
if (Vector2.Distance(transform.position, currentPoint.position) < 0.5f && currentPoint == pointA.transform)
{
currentPoint = pointB.transform;
}
}
//This is just something I saw in a tutorial to help visualize the points for ease of use.
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(pointA.transform.position, 0.5f);
Gizmos.DrawWireSphere(pointB.transform.position, 0.5f);
Gizmos.DrawLine(pointA.transform.position, pointB.transform.position);
}
}
Sprinkle in some Debug.Log()s - see what's going on with your values.
Okay, so they're all getting procced, so I'm not sure what the issue is. It's not making it go right, when it should be going back and forth.
I meant log your values, like transform.position, currentPoint.position, Vector2.Distance(transform.position, currentPoint.position) etc. :)
But in any case,
Vector2 point = currentPoint.position = transform.position;
This seems suspect... currentPoint.position is always exactly equal to transform.position, so not only are your point transforms likely moving, but Vector2.Distance(transform.position, currentPoint.position) is likely always 0 👀
Okay, you were right, it was supposed to be currentPoint.position - transform.position;
Though now it just seems to make it go right, hit the point B, then go left and just...go off course.
I'm not sure... this code does depend on pointA being to the left of pointB. And I think it'll also break if speed is higher than the framerate. It also won't be too happy if point A and B are within 0.5 units of one another. But failing those conditions, you'll need to log the values to see what's going on
Debug.Log(
$@"currentPoint: {currentPoint == pointA.transform ? "A" : "B"}
currentPoint Pos: {currentPoint.position}
transform Pos: {transform.position}
distance: {Vector2.Distance(transform.position, currentPoint.position)}"
);
If it doesnt need Rigidbody based movement...
time += Time.deltaTime * speed;
var t = Mathf.PingPong(0,totalTime);
targetObj.position = Vector3.Lerp(start,end, t/totalTime);
Something like this will make it simple
Oh, uh, neat. Where should I insert that, if it's simpler? I'm not opposed to using it, I'd just want to know what I need to cut out to do so.
{
//Creating to the points where the enemy will patrol.
public Transform pointA;
public Transform pointB;
//Rigid body for moving the body.
private Transform targetObject;
public float speed;
public float totalTime;
private float currentTime;
void Update()
{
currentTime += Time.deltaTime * speed;
var t = Mathf.PingPong(currentTime, totalTime);
targetObject.position = Vector3.Lerp(pointA.position, pointB.position, t / totalTime);
}
//This is just something I saw in a tutorial to help visualize the points for ease of use.
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(pointA.transform.position, 0.5f);
Gizmos.DrawWireSphere(pointB.transform.position, 0.5f);
Gizmos.DrawLine(pointA.transform.position, pointB.transform.position);
}
}```
Okay. I'll give this a shot, thank you!
edited just now ^
It is a single missing line causing all of the errors btw
Oh, it is?
If you copy pasted the above code, then you missed everything that should come above it.
The using statements I mean
Oh, gotcha
Ah I see the MonoBehaviour error is on line 1, so yeah. No usings at all
Okay, so that's inside Unity, but getting this error, and the sprite just dropps to the ground.
Something on line 21 is null.
NullReferenceExceptions are extremely common.
So get to debugging and figure out what reference on line 21 is not assigned
Debug.Log or the debugger with a breakpoint would tell you immediately
Okay, I've got it moving.
Okay, this part is done. Thank you everyone for your assistance with this.
hi i need help a bit im trying to change color on a texture using this, i did create a new texture at runtime, with RGBA32 format but idk why the alpha channel just reduce the value of the color like this
i did tick alphaIsTransparency when creating the texture
not im not sure why
Maybe you should explain what has happened and what should happen instead.
oh yea my bad so basically instead of the transparency like this, the alpha doesn't change the transparency but the value instead basically darker/ lighter
So if the alpha was zero, what would you see?
(I understand that you'd want it to be invisible but what actually happens instead?)
Can you show the inspector for the material?
sure
What shader? Is it a transparent/defuse shader?
i dont think so it just this
I'm a bit occupied but I'm pretty sure it's to do with a setting. Try following the shader transparency docs https://docs.unity3d.com/Manual/StandardShaderTransparency.html
So in my case, I have a level, and in that level there are entities. Enemies, collectables and structures are entities. If a player kills an enemy, or collects a collectable, or destroys a structure, I need to track that so when the level is reloaded the state is maintained. How should I go about doing that?
As a start I was thinking of creating a Entity ScriptableObject for each type of entity. The Entity SO's would have some entity ID, a reference to the prefab, and any other useful data about the entity. I would then have a EntityInstance SO to represent an instance of that entity in the level. These SOs would contain an entity instance ID, and a link to the Entity SO which should be spawned.
I would also have a EntityManager in the levels which would have a list of these EntityInstance SOs. On scene load, these managers would be given some LevelData, which contains a hashset of IDs that represent the entity instances that are still alive. For each EntityInstance that it has, the EntityManager checks if its ID is included in the hashset. If yes, spawn, if not, don't spawn.
This sound good?
Anyone have a good tutorial on how to create 2D armor overlays on my humanoid sprites?
put another sprite in front of the base character?
Seems a little cumbersome, but I might be missing something. I'd say just implement some interface ISaveable on all such objects that you pass a LevelData when you wanna save/load and they write/read what they need there. It might have a Dictionary<id-type,object> or just a HashSet<id-type> if you only care about the "is destroyed/collected" thing, and you'll add data by ID there. Aaand yeah, you'll need a system that assigns IDs to these objects automatically, which might be 10% annoying, but once you have it - you're good for saving whatever you want, I think. 🤔
Well, that's the case where you do all the setup on the scene and then you destroy the already collected things... the other direction would be more optimal if you care and better if you wanna randomly spawn those objects anyway... in which case your idea is good, but I think it can go without all those SOs and just have a manager with prefabs, and it can auto-assign IDs and all that as it instantiates them and call some initialize method 🤔
Hi, I have a voxel game with a bunch of chunks, i'd like to have all of these to be asynchronously updated, like all these chunks dispose themselves if they are too far from the player, but i dont know how to create a asynchronous method without an await inside
dont cross post
Yes exactly
async void method should work
Or a coroutine
Or just a condition check in update
Asnc void didn't worked because I did not have await in the method
I used a task.run but now I have another issue... Because I have a bunch of objects and small updates it creates a bunch of tasks and makes it even worse XD
I will need to pool the tasks and computation
Wdym? You don't need an await..?
If it requires you to use an await, then you're doing something wrong.
If their is no await, the method will be executed synchronously even with the async keyword
No, it wouldn't.
Though, in unity it would be executed on the main thread, so sort of, yes.
You do need an await inside the method of course.
You can await Task.Yield() for it to yield until the next frame.
i could yes, but the issue is still the same, i now have too much tasks creation, do you think we can pool tasks ?
Share your code. At this point I've no clue what you're doing.
You don't need tasks if you execute it async on the main thread.
The code is a bit complicated, here is a simplified version :
public ChunkManager{
/// Create a bunch of "chunks" and give them the player camera
}
public Chunk {
void Update(){
if(isTooFarFromPlayer()) isVisible = false
else isVisible = true
}
}
but i have like 8 000 chunks
Where are you creating the tasks that you're talking about?
on the update of the chunk
https://pastecord.com/ugufuwyvaj.cs
The chunk code
private void PlaceTile(int x, int z)
{
Vector3 position = new(x * TILE_SIZE, 0, z * TILE_SIZE);
GameObject tileInstance = Instantiate(tile, position, Quaternion.identity);
Tile tileScript = tileInstance.GetComponent<Tile>();
tileScript.Position = new Vector2(x, z);
tileDict[new Vector2(x, z)] = tileScript;
}```
i have this function to create new tile game objects. each tile has also a script attached with fields such as position. I want to make a dict using the pos and Tile object as key-value pairs. however `tileDict[new Vector2(x, z)] = tileScript;` throws an error saying "NullReferenceException: Object reference not set to an instance of an object"
does anyone know how to make particles splat onto surfaces? im trying to make a blood splay that prints onto surfaces but I cant find any ways online, any help would be great
This is the chunk manager code, not chunk code. And also, it doesn't even seem to be complete? Where are you storing your 8k chunks?
hopefully the log is spewing errors at you with this because this has no chance of working with Task.Run
your tiledict is not initialized
whoops, thanks
Yes, the naming is not correct, but chunkmanager is on each chunk. Its complete, im storing the chunks in the following file :
https://pastecord.com/gukopozulo.cs
This is where i create the chunks :
https://pastecord.com/hylyzusyce.cs
I have no logs but have some issues in some points yes, but its not the most problematic part, having it asynchronously take more performance than having it synchronous
I guarantee you, even if this did work, this will have far worse performance than doing it all on the main thread. You might have a chance if you were using Jobs and doing the distance computation there, but I think the whole strategy is fundamentally wrong
are your chunks not arranged in some order?
not sure about this
Yep, because it was something that is not related to the player action directly, i thought i could send it to another thread to ensure spawning and despawning a chunk shouldn't lag the player
First of all, most of unity API you can't call from a background thread. Seeing how destroying a GO is the main part of what you're trying to do, that's not gonna work.
Not to mention that you're probably gonna get a hell of a race conditions.
race conditions ?
oh...
To answer your initial question, you can destroy the chunks async on the main thread - over several frames.
It can be as simple as an current iterated chunk int in your manager and iterating the chunks in update with that index. Then you limit how many chunks you want to iterate per frame.
Google. It's too much to explain here.
oh okay i see, so i would iterate through chunk in the VoxelTerrain class instead of inside each chunk
i seen what is it, i didn't know the term but know what it is.
I don't see much where i would have race condition, because each chunk is looking for himself, the only thing that could change would be the position of the player, and even that would not create an issue, i dont have much shared data
You might have a race condition if you access any of the chunk data from the main thread, while it's being destroyed(not that it's possible on a background thread anyway).
Ohhh that way, yeah I understand the issue
Hello I need help with my game design, as everything breaks when I create a build for an android game on my macos. Everything is out of position and not set in the positions I placed them. Can someone please help me with this?
What are the things that are out of place? UI elements?
This doesn't sound like a code question. Try #💻┃unity-talk and make sure to explain/provide information. You shouldn't be looking for someone to fix your problem but rather just post your problem and anyone who knows how to fix your problem (provided you give all of the necessary information) might do so.
(I'm assuming it's a screen ratio / anchor problem.
why should I lol
Perhaps #1157336089242112090 would make more sense? Not even sure if that would be ok
All the UI elements but I figured out how to fix it. Thank you tho!
My bad just joined the server and was figuring it out. Will make sure to ask my questions in the correct channel next time.
Hi, is there a way to find out more about the stack of calls to my functions in a crash dump?
My game crashes at a random moment, while nothing useful has time to be recorded in the log file.
Did you make a development build?
yes
and what do you see in the log file when it crashes?
usually a hard crash wouldn't come from any C# code
That's more likely to happen from lower down in the engine itself
The person who had the crash bug didn't even have a folder on the way
"AppData\Local\Temp.......\Crashes"
everything is written to the log file a moment before the hang and departure
if it "hangs" before crashing it might be an infinite loop
you don't have to, it's a good feature support to have in rider
that's the problem of finding out exactly where, because not only our code is in the project, it can also be code in assets
yeah just saw it was rider looked like a sus link at first lol
I did it, I dont even use rider
hehe thanks
hi guys
i added a render texture camera to my project and now i have 3 cameras.
One is an overlay camera that only renders some parts of the UI
antoher is the main camera that renders to a texture
and the 3rd is the camera that shows to the player the rendered texture
now at first all my interaction were off and i found a solution by changing the physics raycaster with a script i found online. The problem is with the overlay camera where the drag event position seems like they changed with the new camera added ( the one that shows the render)
here is a before and after
and the script i used before is a simple screentoworld point of the mouse position
public void OnDrag(PointerEventData eventData) {
Vector3 screenPoint = eventData.position;
screenPoint.z = planeDistance * 0.8f;
dragPosition = overlayCamera.ScreenToWorld(screenPoint);
}
}```
how should i edit this to make it work on the new camera? The script i found that changes the physics raycaster is this https://github.com/riveranb/UnityRTEvents/blob/master/Assets/RTPhysicsRaycaster.cs
it uses ViewportPointToRay instead of screenpointToRay
in addition the overlaycamera has a canvas in screen space camera since I'm rendering 3d elements in it
hope anyone can help
Hi all, I'm trying to update an animation layer's mask via code - How do I do that?
Can you be more specific about what you mean by "an animation's layer mask"?
Sure thing. In an animation's animator component, you can set up layers, and give each a weight and an avatar mask. I would like to change that avatar mask via code at runtime.
my usecase - I have a baseLayer with an avatar mask that masks just the upper half of the body, but I only want this in effect, when the character is holding something with their upper body (eg. a gun). When they're not holding said item. The baseLayer's avatar mask needs to be empty so it plays the regular set of animations without any masking.
You mean this?
https://docs.unity3d.com/Manual/AnimationLayers.html
Yep that's the one. Just need to know how I can change the avatar mask on the animation by code
I think you would use this:
https://docs.unity3d.com/ScriptReference/Animator.SetLayerWeight.html
For example have two layers with different avatar masks. Have one with a weight of 0 and one with a weight of 1
Swap them when you want
If I understand what you mean
Yep that would work, but then I would need to create duplicates of the baseLayer for every type of masking I need. If I can just set it's avatar mask to none during runtime, it'll save a bunch of work
I'm just not sure how to get access to it at runtime
that seems like it's an unity editor only thing
I don't think I have access to that via the runtime
It's part of https://docs.unity3d.com/ScriptReference/Animations.AnimatorController.html but you only can get the RuntimeAnimatorController at runtime AFAIK
hello i wanted to ask if there is a solution for corner collision with gameobjects,i have been looking and trying to code it,the results are not working as intended
the intended results is that the player object(being a square2D) when it collides with another player with a corner first it will kill the opponent, however what happens is that it works when it wants too
!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.
Cant view that on mobile
I have a 3d labarynth generator that changes dynamically, but I don't want the walls to be able to change while they're on screen, is there any way to implement this?
you can check if something is visible ?
But I have to disable the renderer to hide the wall, then it doesn't work
At least I think
You'll have to specify more at what the issue is, rather than "it works when it wants". You have logs but you should print out more useful stuff like what it hit. Printing out just literal strings isnt gonna tell you much. Also this looks incredibly hardcoded
What does hiding the wall have to do with your initial question?
I don't want the walls to be shown or hidden while they are in the camera's view
isVisible ignores objects that are in the way
I want it to be able to detect if an object is in the way causing the wall not to be visible
Actually if anyone has a better idea it would be appreciated as this method makes it incredibly cheesable by just facing away from a wall and walking backwards into it
I'm somewhat confused by what you're actually trying to do so heres a link on detecting if something is visible
https://discussions.unity.com/t/how-can-i-know-if-a-gameobject-is-seen-by-a-particular-camera/248
As for your last message, you could just do some physics query or have a trigger collider to let you know which objects are close to the player. Then just dont change walls which are also very close
So am I to be honest, I ended up combining isVisible with a translucent material that is basically invisible to the naked eye but not to the isVisible check, and I also added the radius around the player.
Hi my animation events are firing twice and I have no idea why? Any help?
What makes you think they're firing twice?
Well if I stick a debug log on the method that receives the event, it prints twice
Ok so - can you show us the inspector of this object with the animator?
This is the event
Ive checked, there is only one event in that inspector, its not two overlapping
I would like to see the inspector
not of the event
And I used debug log to verify that there is only one source, a single component on my main player char
Sure which component?
which script has the function?
SoundController
how did you verify that exactly?
Have you tried Debug.Log($"Animation is called on {GetInstanceID()}", this.gameObject);?
Not instanceId, let me see
Called twice, same instance ID, and same gameobject name (which I tried earlier)
Alright so how are you p[laying this animation clip exactly?
Perhaps the animation is quickly starting twice or something
what does your AnimationHandler script look like
Its unrelated to this essentially, its more for procedural movement of the character, not the animation states itself
This is the animation state to transition to it
I guesss it could transition to itself?
Wait
There is a checkbox for that let me disable it and see
Ah
That'll be it
Thanks for rubber ducking for me @leaden ice
nice
Any ideas why my static variables (inside a public class) is not saved between scenes in WebGL builds, while it works just fine (between scenes) in the game preview thing in Unity?
public class StaticItems : ScriptableObject
{
public bool looted;
public string itemName;
public Sprite inventoryIcon;
}
From console we can see that the item is set to true, and then we switch scene back and forth and it's false. Could it be related to this part? Unloading 34 unused Assets to reduce memory usage. Loaded Objects now: 2107.:
interact_with_item.cs: looting the staticItem - staticItem.looted is:True
intro_test.framework.js:10 Trying to get length of sound which is not loaded.
intro_test.framework.js:10 [PhysX] Initialized SinglethreadedTaskDispatcher.
intro_test.framework.js:10 UnloadTime: 11.255000 ms
intro_test.framework.js:10 Unloading 0 Unused Serialized files (Serialized files now loaded: 0)
intro_test.framework.js:10 Unloading 34 unused Assets to reduce memory usage. Loaded Objects now: 2107.
intro_test.framework.js:10 Total: 2.835000 ms (FindLiveObjects: 0.105000 ms CreateObjectMapping: 0.045000 ms MarkObjects: 1.985000 ms DeleteObjects: 0.700000 ms)
intro_test.framework.js:10 [PhysX] Initialized SinglethreadedTaskDispatcher.
intro_test.framework.js:10 UnloadTime: 1.665000 ms
intro_test.framework.js:10 Unloading 0 Unused Serialized files (Serialized files now loaded: 0)
intro_test.framework.js:10 Unloading 29 unused Assets to reduce memory usage. Loaded Objects now: 2090.
intro_test.framework.js:10 Total: 2.080000 ms (FindLiveObjects: 0.145000 ms CreateObjectMapping: 0.070000 ms MarkObjects: 1.445000 ms DeleteObjects: 0.420000 ms)
intro_test.framework.js:10 interact_with_item.cs: staticItem.looted is:False
Yes, probably due to the unloading. Generally you do not want to mutate SOs. Treat them as immutable as much as possible
You should probably just use a POCO (plain old c object. Just a class) for this
Oh, I see. I thought it was the "standard" kind of object for data persistance between scenes
No, definitely not. It should not be used for that situation at all. People SOMETIMES try to force it, but it is bad practice, and not recommended
Quoth the manual:
When you use the Editor, you can save data to ScriptableObjects while editing and at run time because ScriptableObjects use the Editor namespace and Editor scripting. In a deployed build, however, you can’t use ScriptableObjects to save data, but you can use the saved data from the ScriptableObject Assets that you set up during development.
Data that you save from Editor Tools to ScriptableObjects as an asset is written to disk and is therefore persistent between sessions.
Mind blown, thanks dude
SOs are kinda like prefabs. Just variants of data. Use them when you want to swap in and out presets of data in the inspector
Cool, I'll check out POCO, thanks again!
Keep in mind, to persist between scenes, they need to be referenced. POCOs will be garbage collected like normal when no references exist (like when a scene is unloaded). So look into additive scene loading or DontDestroyOnLoad as well. The object referencing the POCO needs to be in a scene that is not unloaded
Great info, thanks
So much new stuff, I just want to create the best game ever (TM) on my first try with unity 😉
Kind of funny how it's recommended by: https://gamedevbeginner.com/how-to-make-an-inventory-system-in-unity/
Huh... indeed. This seems peculiar 🤔
He does go on to say that you can separate the data which can change from that which doesn't using a POCO which references the scriptable object... But I don't understand what he's getting at with the Inventory SO there, unless he's just saying that you could use it to configure default inventory contents
I don't think that manual quote is directly related to data persisting in SOs between scene loads.
@inner charm I believe you can avoid SO being unloaded if the next scene is referencing the SO early enough.
Ah you're right - it's just talking about persistence to disk...
I've often heard it discouraged, but is treating SOs as mutable runtime data just a matter of personal preference, if you are aware of the caveats of doing so?
Oh, that seems correct
Not aware of technical reasons against mutation beyond those lifetime and editor behaviour caveats. Some people are very into stateful SOs.
I see nothing wrong with it, after all SO's are the only data structure supplied by Unity which are both editable in the Editor and live outside of the scene context
Interesting... I feel like the majority of conversations I have witnessed err towards just treating them as immutable data. But I have no horse in this race as of yet. I'll have to poke around some more. I appreciate the insights 🙂
Caveat is that in Editor environment you're mutating your asset and it will persist, unless you instantiated your SO.
And if you do instantiate your SO there is no real reason to use SO.
Though same rules apply to prefabs
My internet is having a real struggle at the moment and it's unclear if I'll be able to continue this conversation, but are you saying instantiate a SO as in like Instantiate()?
Yes, looks cursed? Yes. Is it cursed? Yes.
Fair on all counts 😅. The discrepancy between the editor and runtime behaviors does seem mighty off-putting
Thing is that using SO directly means you are also coupling "initial data" and "runtime representation", which is not always same.
and cleanup issue when you having some weird event stuffs on it, etc
It certainly adds up to a very persuasive argument against doing so. I'll have to find some time to experiment a little more and see if I can appreciate any qualities of stateful SOs in practice, but I do think I may be leaning in the opposite direction.
My intended use for SOs are to check them if certain conditions are met, that for example allows progressions to another scene
So when I loot a key, that scriptable objects looted property is true. This means that the key is never displayed again in it's original location, and it also means I can pass a certain door, and progress to the next scene.
This works great in the editor, I can loot the key and move back and forth between the scenes, but in my build it "forgets" the scriptable object when switching scenes ... 😦
First line in the manual:
"A ScriptableObject is a data container that you can use to save large amounts of data"
Later in the manual:
"In a deployed build, however, you can’t use ScriptableObjects to save data ..."
The first line refers to the editing time. It is indeed a good way to store data that would remain mutable during the game.
i think in deployed builds also scriptable objects works fine to save data. but i use for small amounts ony.
No they don't. They are just an asset. Thinking of modifying them is as crazy as thinking of modifying a mesh or a texture asset and expecting the changes to carry on to the next session.
the whole conversation above was specifically how SO are not to save data in a build also
I don't think it's all that crazy to expect the compiled version to act like the editor version
But that might just be me being an enthusiastic noob 🙂
id say just the behaviour having to be figured out is a good enough reason to keep them as immutable data. At least for me, id rather just go along with what i know of using plain c# classes than run into a random bug
There are many differences between editor and a build. SOs are one of these differences. In fact, they're specifically an editor tool. I guess there's a lot of misconceptions around them.
Am I missing something from this? It should be working the same as the others I've got but for some reason nothing happens :/
Sigh, this will be another argument for my team to switch to UE instead. It's a pity, I started to like Unity 😐
So you think SOs(there are no SOs in unreal) in unreal work the same way in the build?😅
I can guarantee that any similar feature in unreal would also not work as you expect.
Why would you say this?
Add logs. Maybe isCasting is false so it returns early.
Also do not use ?. on anything deriving from UnityEngine.Object, it doesn't work properly (it bypasses the "destroyed in the scene, but not null yet" state of Unity objects)
which suuuucks
isCasting is just a class variable of active, it should be enabled & disabled acording to when the spell is active and inactive
Why is there a random } lmao
Oh they're just messy nvm
Yes, but at the time the method runs it might be false.
Use logs or the debugger to find out if the code runs
It runs every frame, no?

If it's not casting I don't want it to run, will it still not run when isCasting is true?
It will run if it's true, that's guaranteed.
But you said that "it doesn't work" so you need to find oit why
It will not overlapsphere if isCasting is false, which is why I'm asking these questions
Because I don't see why you'd bring UE here. SOs don't make Unity inferior to UE in any way.
You can express those opinions without stating that I think something I don't think - if your opinion is solid it should stand anyway.
(I also agree that I don't think that this makes unity inferior, however this will give my team more reasons to bash unity)
Argument is that you shouldn’t bash the engine for the reason that you are using features in unintended way 🤔
Got it working without much stress, the 4 debug messages I had spamming every frame were causing just a tiny bit of lag
(From around 90FPS to like 15)
Not sure how that's related to the issue in any way, but glad you got it solved
Next time make sure to include more information on what the issue is, though
hey im trying to change my projects editor version from 2022.3.8f1 to 6000.0.11f1 but i got this error what should i do ?
and i tried before to switch the unity editor version but when i tried to build before i always got a gradle build error
Are you planning on using the package it's mentioning in the error? multiplayer.samples.coop
why is my audio crackling?? I've already disabled doppler effect tried changing to streamed and yet still this happens I didn't do anything prior but it just started happening (though I did add a lot more objects so that may be why) but otherwise I have no idea.
im not sure to be honest, i use the unity relay multiplayer, so im thinking its needed for relay ?
Okay, so in that case let's not remove it, so you'll need to install Git on your computer to proceed
so do i just install git from my browser and restart unity ?
Yep, restart your computer in between, because Git makes change to the PATH so it can be executed from anywhere
ok i will try and comeback
and do you know anything abouut the gradle build fail when im trying to make a new build ?
There will be more errors on a failed build, check the console for other messages. You'd want to ask that in #📱┃mobile though, if the issue does not come from your own code
okay thanks a lot man
heyyy im back :D, what should i do here
Make a backup and update all
it says that there are deprecated packages in package manageer and shows me this what should i do ?
do i just continue to use it like normal ?
remove it, use the Visual Studio Editor package
oh i just realised its not even the normal visual studio
i dont use visual studio code
That's one more reason to get rid of it
VSCode uses the Visual Studio Editor package too nowadays
Yeah it's package code (TextMeshPro here). Close the project, go to where it's saved and delete the Library folder, and open the project again
That will force a full reimport of package contents
okk it will take longer though right ? cause its gonna reimport everything again or something
Yes
ok i will try that, thank you a lot again :D
i got the same errors even after deleting the library folder
Ah these don't come from the library folder. If you don't need the TextMeshPro examples, delete the folder mentioned in the error messages
Assets/TextMeshPro/Examples_Extras
yeah i dont think i need them i just use tmp for the ui stuff
Yeah when you use it for the first time it asks you whether you want to import examples along with the base stuff
do you know what the fmod sub-system is ?
It's a sound engine that can replace the one Unity has built-in
#🔊┃audio might be able to help you for this one
I have issue with scrollbar on IOS devices. In WebGL and android it's works fine but in IOS it's laggy and jittering
But it's still default Unity Scroll
thankss
without using the dampen settings et al, exactly how were you supposed to make it such that the cinemachine virtual camera rotates with the follow target focused in the center?
Anyone have any good design patterns they use for save/load systems? In particular, how parts which rely on the save state get their references.
do you know anything about this or where im supposed to ask about it ?
open task manager and force close unity editor. alternatively restart your pc.
i do it the stupid way and serialise a dictionary
at the start of the game i call Load() in my save system
Like a dictionary that holds all the various refs to things you have saved? Sounds pretty good tbh
my save system is a dictionary<string, string> so I end up casting stuff whenever I do numbers 😦
but syntax is very clean
dawg 😭 🙏
SaveSystem.variables["username"] = "uldynia"
and it will get written to the save file next time
uh if your unity is on an external drive it probably has issues
its not 😭
broad statement hold on imma see where the logs folder is
you mean editor logs?
idk if its a hubs issue or editor issue
do you know anything about this ?
what is mandetory ASLR?
the problem is im not publishing on ios either
i want to publish on android and windows
check your package list because apple sdk is in there
forgot to mention: my savesystem takes 10% of my game's cpu usage(or 10% of the system's cpu, idk how profiler works). I need to change this.
users here said that I should keep the file handle open.
Hello guys, how can i update Google Play purchases? Is it enough to update Unity com.unity.purchasing package?
Any idea why this gives this error? Using the .jslib plugin at Assets/Plugins/WebGL, trying to call the function from that plugin
sorry which function are you trying to call?
First three on the second screenshot
used this same plugin in an older version of unity for another project
called it the same way
for some reason this gives an error now
can you narrow down which one it is exactly?
i.e. by commenting them out one by one (is it all of them)?
rebuilding takes a lot of time, but if that's the only option alright
I guess I'm trying to see how you determined it was exactly these functions causing the issue
previous build worked fine, after i added those three it stopped working
also sorry if i sound rude, did not mean that
no worries, didn't feel any rudeness
Can you maybe show more of the js code? I think this may be a problem mostly on the JS side.
what is "Google Play purchases" and what does updating mean in this context?
This sounds very much related to #📱┃mobile though
Edit:
Oh I see you're talking about IAP?
that's the whole file, just these functions
does your HTML file have any javascript?
sorry for late response, i fixed it, it's a silly mistake
it was this thing
oof
anyone know of any .net libs i can use to make a vitual audio input from a unity application, or even a .net lib to make one myself?
can someone please help me, im currently making a game, but i have absolutely no knowledge of coding so i just watch some tutorials, but now i want subtitles to show when i walk trough an audio trigger but the subtitles wont show up
Something that may help you in the future:
- Open your jslib/etc in vscode
Ctrl+Shift+P>Change Language Mode>JavaScript- Now you'll have some basic JS coloring/syntax/partial error help
you would have to show the setup you currently have and any related code. Also this should be moved to #💻┃code-beginner
Hi, I have an object which acts as the collider and rigidbody for a gameobject but doesn't hold the main script. It's de-parented on start. What would be the best way to link a collision on that object back to the object with the main script?
oh sorry, ill go there
NAudio might have that feature
its complex library but powerful
It's the sphere in this case, the player vehicle holds the controller and manager script
Ah no worries
yea i was told about that before but the link they sent was bad and didnt go anywhere.
Can i ask about NGO stuff there as well
ngo stuff in #archived-networking
though frankly from your question you should wait a while before doing networking
the github?
https://github.com/naudio/NAudio
yea it was on reddit and it just didnt work its weird. XD
Ik what im doing dw i just want to know the least janky way to do it haha
you might need another plugin with this though
least jank is always using event systems
yea maybe, im not really seeing anything to make a virtual audio input e.g makeing my own virtual mic to use in other applications
I dont think i could do it with event systems
Basically i need to access the manager script from the sphere when it collides because i need to send data from the object it collided with to the manager to be stored in a network variable
But i dont want to just have a script with a reference on the sphere because thats not great
yes you do that with proper referencing
who says that
use as many scripts as you need
anything else is nonsense complexity added on
Fair enough you're right i am overcomplicating it
I'm still trying to understand exactly what you're going for here
Are you going for something that already exists like "virtual audio cable"
Thank u
but you need a script on the sphere to detect the collisions anyway
A classic case.
Most people eventually will have to write some JS at some point in their career, and a lot of people go "okay I don't care about JS, this is just an one off task, I'll just raw dog it with notepad and zero tooling" and wonder why they have a bad time and blame it on "JS bad."
There are good reasons why code channels here require people to have IDE set up to receive help, because practically any programming language is terrible to work with without tooling, JS or else.
I'm building a hex-based world where some tiles have integer based movement costs (usually just 1 or 2). Should I use NavMesh for this or just roll my own pathfinding?
(I've never used navmesh)
probably your own with A* if you need precision
just dealing with tilemap though is annoying
Yeah.. I think I previously wrote some hex based nav code but.. I remember it being a big pain in the butt
the redblobgames snippets were kinda difficult for me to adapt to unitys tilemap coordinates on hex
Like having to convert to a custom coordinate system.. cubal? cuboid? from some website
redblobgames was it, I think
yes redblob is goat
just a pain how unity did their tilemap system the formulas dont translate 1:1
yeah
I'm not sure I'll use unity's tilemap system.. for this game the world will be a pretty small set of hexes and won't change so.. tilemap might not be the right hammer for this nail
if you are able to make your own would be easier
oh yeah I vaguely remember writing this
I just...too much math for me
and basically just being like "🤷♂️ well redblob says it works"
no idea what that chunk of code does tbh
hah yea
so im finding alot of things, it will allow me to make unity work with virtual audio devices and be able to select them, however it cannot make them, so ether ill need to make my own driver OR i need to find a drive and a .net lib that allows me to make as many as i like in this case i dont see anyone useing more then 6. but ill also need to be able to make more as well as ill need to be able to make virtual outputs so that other applications can feed in to this program there for allowing me to make my own custom DAW, onec that small little issue if figured out e.g how i want to do it, then ill be set.
I got pretty far with the hex movement though, and few basic attack types / patterns
haha "black god damned magic"
yeah maybe I'm afraid to open this can of worms again, i dunno
https://www.redblobgames.com/grids/hexagons/#range-intersection
this and everything under is basically what I needed and it made my head bust
yeah
in this (year-old?) chunk of code i wrote, it's basically that:
looks like something that can take a tilemap x and y and convert to/from the cube/axial Q/R/S
i remember it busting my head but.. theoretically? once I do the hard work of A* and conversion from x/y to q/r/s it "should" be easy to consume
point top?
it looks like i have world-to-tilemap-to-hex mapping working in this old demo
oh right, orientation of the hexes
yeah it seems like i was doing point top too
this project i'm working on now will be in 3d, but the "map" will be 2d internally.. probably will do cinemachine and isometric
the models i have came with animations and everything
i think so? i can't exactly recall xcom, I didn't play it
remind me again - turn based strategy sorta thing?
grid turn based action strategy game
yeah
its remind me Ratch & Clank
so this game is actually just going to be a web demo of a board game
the assets come from a video game that didn't succeed like a decade ago
i probably ought to not share it though 🙂
... and like that poof he was gone
🙂
I feel exclusive to have seen the sneak peek 
in any case! I suppose i'll have to warm up my brain for the hex stuff again.. seems better than using navmesh
ha
it's on a pretty short timeline and it'll be public, so.. I'm sure you'll see me post about it from time to time again 🙂
same i feel like vip
navmesh just feels clunky for a hex but ig it can work
its a* anyway at the end of the day
i'm trying unity6 for the first time, given URF is irrelevant for this, and the client wants it purely in web
apparently unity6 has some great improvements to "Unity Web" aka WebGL
We'll see. 👀
Oh yeah heard that too. Looks promising
I'm sorta diving all-in on this one.. the project will be with 3d assets, animations, etc.. if Unity6 can handle this all and get me 30+ fps and a reasonable load time.. I'll be impressed
Although tbh more with myself since I'm a 2d game dev, this 3d shit is all new to me. I'm a dinosaur. 😛
besides the assets its not that much different in unity thankfully
Yeah, just a lot of stuff to learn.. stuff I'm "familiar" with but not an expert in.. Like, I'd say I know my way around the UI framework pretty well.. but meshes, cinemachine, and rendering is all stuff I haven't really needed to really dive into yet so.. it'll be a journey.
what isn't working? Also what are these two unrelated pieces of code and how are they related?
also why is that first coroutine... not actually yielding on anything?
Doesn't seem necessary for it to be a coroutine
Well I'm not sure why but I thought it needed to be in one, didn't change anything tho. It just instantly loads the scene
well you haven't shown enough here for us to understand what it is supposed to do differently from that
the second code is when all the other stuff is loaded it previously directly loaded the game scene which causes some lag spike, I thought I could async it and then activate the game scene at that point
the second code is when all the other stuff is loaded
But.. hjow are you checking that? Where is it running?
Show the rest of the code
!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.
in update it checks the progress of a bunch of data requests handled by the data manager, if all the checks pass and all the data is loaded it waits for the animation to get to the end before loading the next scene
if (!LoadingAnimator.IsInTransition(0) && LoadingAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime > LoadingAnimationReferenceTime + 0.56f)
{
LoadingAnimationReferenceTime = -1;
LoadingOperation.allowSceneActivation = true;
}```
@leaden ice
there's not much else to the code idk what else you are looking for
the loading screen takes time to fetch the data from the server, so the line
LoadingOperation.allowSceneActivation = true; is only called once all that and the animation finish
This code is just sitting by itrself in a text file alone?
I have no idea when this is running
in update ...
Well time to Debug.Log the animation reference time and what normalizedTime is coming out of your animator etc
(you could/should probably use an animation event for this)
umm no all of that was fine. I had SceneManager.LoadScene there before, not to mention there are other checks before it, the game scene shouldn't be loading instantly, the async thing is just not working idk why
and the animation is fine, it is very specific to have a smooth transition
alright I fixed it
just don't put LoadSceneAsync in Awake
how can i make onvalidate run only after a value has been completely changed in the inspector for an int let's say, and not while typing the integer into the inspector field, thus making weird valiudations. e.g.: i want to enter 123, but it starts validating after i've typed 1
In a project where scenes are never loaded additively, what's a working flow to clear all data from a static class whenever loading a new scene? My problematic constraint is it has to be prior to awake on any object. Hooking onto sceneloaded fires after awake on monos in the scene
I understand I could manage with a mono singleton but I'd like to know if it can be done differently
(with a custom editor)
better to just not use static variables as they have no tie to the Unity scene lifecycle at all as you are seeing
I find myself with a decent amount of monos living in the scene just to support the solver. I was hoping I could find a workaround to keep the count lower. Anyhow, thank you
thanks so much
hey, could someone give me a hand with structuring an item system? right now i'm using a system with abstract classes. it has a scriptable object base with a total uses variable and an abstract use method. each different item works off of this, but the problem is that each method requires different parameters for the use method
i want to be able to randomly pick them so they should all have the same base class
each method requires different parameters for the use method
Why? What are the parameters? Why pick an abstract class for this
Inheritance usually ends up being an antipattern for an item system
It's usually better do go with a composition/tagging system
how would that work? ive not heard of that before
Imagine you have:
Item < Weapon < Sword < WoodenSword
< Armor < Shield < WoodenShield
How do you check if a given Weapon is made of wood? Or if an item can be held? This structure doesn't help us
Instead just make something like:
public class Item {
public string name;
List<ItemComponent> components;
}```
or
```cs
public class Item {
public string name;
List<Tag> tags;
}```
Tags can be something like:
```cs
public class Tag {
public string name;
public float value;
public bool ValueAsBool => value != 0;
public int ValueAsInt => Mathf.FloorToInt(value);
}```
Then you could have a "damage" tag, a "wooden" tag, a "holdable" tag
etc
durability, whatever you need.
youi can even make these things serializable so you can set them in the inspector
and this doesn't force any particular item to have any particular set of tags
a health potion doesn't need a "damage" tag
ahh i think i get u
but it might have a "consumable" tag and a "healing" tag
and you could have methods inside those tags that dictate how you'd do that?
well the method wouldn't be in the tag
but your player might have an Attack() method that does something like:
if (equippedWeapon.HasTag("Damage", out float amount)) {
DealDamage(amount);
}```
in this scenario Item has a function that is checking if a given tag exists and getting its value if it does
You can also do some fancy stuff with enums and delegates in a modified version of this if you want to get fancy
this is very clever i really like this
especially because it will save me loads of time as im working with networks
yeah you'll want to set this all up to be serializable then ofc
so for items that spawn projectiles i can use one base method for separate server/client objects
yeah thats all good
im not going to have loads of items its a mario kart type system
Ah I see
another question, could tags have different data to each other?
say a 'boost' tag also had the boost amount and duration
or the 'spawner' tag had the prefab it needs to spawn etc
Hello, i'm having this bug upon swapping between scenes. The first "chess" plane represents the main scene ,3 axis scene represent the secondary scene which i intend to translate between main to secondary.
in the runtime, upon a top click on the "Enter Editor Mode" which aims to move to secondary scene ... it makes the scene 1 infused with scene 2... why is that happening?
are you perhaps loading the scene additively instead of in single mode?
You could add a List of objects ig
and treat those like parameters, it might get messy though
Usually in those kinds of situations I'd be using a separate component on that object
how can i store a game object and not let it destroyed upon loading a new scene? i put it in a singleton class but it resets with new scene
i did use this function on the selected gameobject but i think i could be using it wrong
public class LoadEditor : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void LoadEditModeScene()
{
if (GameManager.Instance.activeGameObject != null)
{
DontDestroyOnLoad(GameManager.Instance.activeGameObject);
}
SceneManager.LoadScene("Editor");
}
public void UnloadEditModeScene()
{
SceneManager.UnloadSceneAsync("Editor");
}
}
I'm using a button to trigger LoadEditorModeScene where i hoped it would store gameobject and load the scene called "Editor"
Show your implementation of DDOL (the Singleton script)
public class GameManager : MonoBehaviour
{
// Static instance for Singleton
private static GameManager _instance;
// Public property to access the instance
public static GameManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<GameManager>();
if (_instance == null)
{
GameObject singletonObject = new GameObject();
_instance = singletonObject.AddComponent<GameManager>();
singletonObject.name = typeof(GameManager).ToString() + " (Singleton)";
}
}
return _instance;
}
}
// Prevent the Singleton from being destroyed when scenes are loaded
private void Awake()
{
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
else if (_instance != this)
{
Destroy(gameObject);
}
}
// List of game objects
public List<GameObject> gameObjectList = new List<GameObject>();
// Active game object
public GameObject activeGameObject;
// MORE nonrelated code
}
public void LoadEditModeScene()
{
if (GameManager.Instance.activeGameObject != null)
{
DontDestroyOnLoad(GameManager.Instance.activeGameObject);
Debug.Log($"Set active object to DDOL {GameManager.Instance.activeGameObject}");
}
else
{
Debug.Log($"There wasn't an active object to DDOL");
}
SceneManager.LoadScene("Editor");
}```Try to log if there simply wasn't an object to set to DDOL
Else you're likely manually destroying it somewhere
The log states that cube zero was set to DDOL
its funny that i don't remember using destroyed in scripts other than singleton class
The inspector for your singleton manager instance likely isn't the same as that which was printed
This looks very unconventional ```cs
// Public property to access the instance
public static GameManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<GameManager>();
if (_instance == null)
{
GameObject singletonObject = new GameObject();
_instance = singletonObject.AddComponent<GameManager>();
singletonObject.name = typeof(GameManager).ToString() + " (Singleton)";
}
}
return _instance;
}
}```
Why do you need to find the object if it's sure to be in the scene and would have set itself to the instance on awake?
Do you've got race condition issues?
Try to avoid accessing external objects in Awake methods to avoid the race conditions (assuming something has attempted to access the manager before it sets itself as the instance)
In fact if you access the manager instance before it calls it's awake, it'll not set itself as DDOL because the instance check in it's Awake would not ever be null.
tldr: if instance is not null when awake is called, the game manager will not be made DDOL
Log this to see if the manager was made DDOL cs // Prevent the Singleton from being destroyed when scenes are loaded private void Awake() { if (_instance == null) { Debug.Log($"{this} has become the manager and was set DDOL"); _instance = this; DontDestroyOnLoad(gameObject); } else if (_instance != this) { Debug.Log($"{this} was Destroyed because a manager already exists"); Destroy(gameObject); } }
i made it to validate that there is only 1 GameManger and only one can access it at a time and prevent loss of data or a change in data simultaneously.
what do you mean accessing External objects? all i've been used gameObject and the instance itself.
Why does the getter need to check if the manager exists in the scene and has not set itself as the instance?
Active GameObject:
None
Current Main Tool:
Tool: none
Current Transform Tool:
Tool: none
Current Brush Tool:
Tool: none
2D Counter: 0
3D Counter: 0
Draw Line Color:
Color: RGBA(0.000, 0.000, 0.000, 0.000)
Draw Line Material:
None
Game Objects:
None
has become the manager and was set DDOL
UnityEngine.Debug:Log (object)
GameManager:Awake () (at Assets/Source/Script/GameManager.cs:52)
UnityEngine.GameObject:AddComponent<GameManager> ()
GameManager:get_Instance () (at Assets/Source/Script/GameManager.cs:25)
BrushKit:Update () (at Assets/Source/Script/BrushKit.cs:44)
My advice would be to not set the instance anywhere else other than in the Awake method and that nobody should be attempting to access the manager (or any other object) in their Awake - relative to external objects.
They should only be modifying values on themselves in Awake with no dependency on other objects in the scene
Use Start to avoid race condition
ahh so probably it's all behind the get functionality emm
aight thanks man for the assistance i will look more into get later on.
but just make things clear,
the whole issue is probably related to Wake or the get?
cause you just made me more confused about it sry
Not a hundred percent certain but the getter looks like a band-aid solution to avoiding race conditions (a manager already exists in the scene but has not set itself as the single instance yet)
i just replaced awake with start but it initalized the values from the beginning
Show the method
if you notice in the editor view, after i added a game object called cube, i have a 3d counter that increased and kept the same after scene swap
The singleton should assign itself as the single instance in Awake. No one should be calling the manager instance in their awake method.
My concern is with this being none after cube zero has already been set as DDOL (it's the active game object) - assuming you're showing the inspector after the log message .
weird thing...
cause this is how i initalize it with these values
and after adding cube 0 and swap i get this while other values are still preserved
Show your console logs
I'm not sure which object being access threw your nre but the game manager with the missing object references indicates that the object was destroyed. When do you call LoadEditModeScene?
i called it upon triggering a button "Enter Editor Mode"
the follow error log message is resulted from attempting to print out the singleton class
yeah the cube doesn't appear cause it is destroyed somewhere
Maybe don't load a new scene that very frame after setting DDOL
I'm assuming you aren't destroying the cube anywhere
would you think that probuilder runtime objects are destroyed automatically upon scene swapping?
like i need to override it
public void LoadEditModeScene()
{
if (GameManager.Instance.activeGameObject != null)
{
DontDestroyOnLoad(GameManager.Instance.activeGameObject);
Debug.Log($"Set active object to DDOL {GameManager.Instance.activeGameObject}");
}
else
{
Debug.Log($"There wasn't an active object to DDOL");
}
StartCoroutine(LoadSceneNextFrame("Editor"));
//SceneManager.LoadScene("Editor");
}
private IEnumerator LoadSceneNextFrame(string scene)
{
yield return null;
SceneManager.LoadScene(scene);
}```
i just tried the new LoadEditModeScene but 😢
the debug is still fairly printing the game object (cube 0) as previous
Set active object to DDOL Cube 0 (UnityEngine.GameObject)
Undo the changes to LoadEditModeScene. Do you've got any scripts that would destroy the cube other than loading a new scene?
Alright, try simply not loading a new scene and see if the active object (cube) is actually made DDOL
public void LoadEditModeScene()
{
if (GameManager.Instance.activeGameObject != null)
{
DontDestroyOnLoad(GameManager.Instance.activeGameObject);
Debug.Log($"Set active object to DDOL {GameManager.Instance.activeGameObject}");
}
else
{
Debug.Log($"There wasn't an active object to DDOL");
}
//SceneManager.LoadScene("Editor");
}```
Check the hierarchy to verify
Here
So it isn't ever made DDOL
it doesn't appear also in hierarchy but it does in the singleton
The singleton is simply referencing an object. The object needs to be in the DDOL scene to not be destroyed on loading new scenes.
public void LoadEditModeScene()
{
if (GameManager.Instance.activeGameObject != null)
{
DontDestroyOnLoad(GameManager.Instance.activeGameObject);
Debug.Log($"Set active object to DDOL {GameManager.Instance.activeGameObject}", GameManager.Instance.activeGameObject);
}
else
{
Debug.Log($"There wasn't an active object to DDOL");
}
//SceneManager.LoadScene("Editor");
}```Try this and single click on the log mesasge. Which object in the hierarchy is highlighted?
it highlight this object here
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
Object.DontDestroyOnLoad only works for root GameObjects or components on root GameObjects.
Set it's parent to null before calling ddol (or you may need to redesign some stuff)
i see
well thanks to you i would not think about it
really appreciate it
i will modify it accordingly in the morning, i will update you about it
it's nap time haha
the issue about it all that i don't want to destroy objects but keep them all. Even after scene swapping, cause my project is aim to help interior designing using VR and meshs shape manipulation
Maybe have Objects (the root scene object) be DDOL and simply have two sets of Meshs: Persistent and Non Persistent
Where you'd manually destroy the children of non persistent on loading a new scene.
so storing the game objects between scenes swap is a must, unless i preserve each game object value to the singleton and rebuild each game object upon returning to main scene
that could also work i guess. i would need to look into dontdestroyonload and scene manger more about it
glad to know that the whole issue is not about singleton class itself
anyway, really appreciate the help and assistance and thanks for your time.
goodnight!
Does anyone know if this is a good way of instancing UI materials? I'm thinking it might leave some cache, but overall, is it a good way to do this?
I'm using URP canvas shader graph
The new material, do you use it only to set the texture?
Or is it a different material?
you could probably try using ProfilePicture.material.mainTexture and flag _texture as your main texture in your shader
you won't have to create a new material
ProfilePicture.material.mainTexture = GetSteamImageAsTexture(ImageID);
I’m using a canvas shader in URP shader graph, do you know if that still works?
yea you should be able to mark a texture field in your shader graph as _mainTex
i think its _mainTex? or _mainTexture
Thank you so much, I’ve been asking around for this, lemme test it
Hmm. I've typically just done new Material(oldMat) and it's worked alright.
Is that improper?
haven't had a usecase where I needed to create a new material instance
usually i just access the component and its material attached and modify its properties
It doesn't work, I forgot to tell you but I need it to have different textures but in the same material
So I don't want the pfp to be like this
But instead like this:
Yeah, I forgot you can do that, I'm gonna switch to that instead of instantiating it
Thanks
But again, by doing this, it does create cache. Is this problem really unavoidable?
Actually, now that I think about it, by making a new Material based off the old one, it doesn't really create much cache does it? I think I'm actually good with this method. Thanks a lot, it works well.
Thanks for your guy's help!
Is there a way to preserve data after modifying a scriptableObject class? Or am I stuck with having to update the SO values every time I make a change to the ScriptableObject class?
Does this mean that people often keep something like a spreadsheet to read into SOs?
I'd imagine it would be the same memory footprint? Not sure. Instantiate is maybe slower to execute. I believe unused Materials are killed during scene reload.
Otherwise you need to keep track of them and destroy when needed.
I seem to have done something weird to encounter this problem, I just tried to recreate it but it doesn't do this anymore
Do you mean, you want to restore the values after you change the fields name or something?
if so, there's a provision for that
[FormerlySerializedAs("oldFieldName")]
I figured out why the SO values were wiped, it's becuase I tried to change the same field on different SOs en masse, so what happens is that other than the field (let's say there's A, B and C) that I specify for example C --> then A and B become empty
Normally if you want to have mutable data on SO you instantiate it and use that instance, modifying it. When you need to restart you instance original again.
Not sure what you are describing there. The only way to wipe the data from instanced SO fields (across all instances) is to rename those fields. If you want to rename the field without erasing data, use https://docs.unity3d.com/ScriptReference/Serialization.FormerlySerializedAsAttribute.html You can remove it later.
I didn't know you can instantiate them
Hi, I have a simple question,
The application that exports the package we created for the Unity asset store , it asks if it is dependent on any asset store asset, but does it automatically get my dependency on newtonsoft json automatically from the manifest file in the package manager?
Or do I need to add that dependency while uploading my package from somewhere?
I think the point of that package being built in is so you don't have to include it
to avoid every asset that uses it importing it's own version of json
when you use the Asset Store Uploader there is a check box 'Dependencies use package manifest' Select that then you can select the package dependencies you want
@spare island @knotty sun thanks a lot
Hey everyone.
quick question about async await.
I am trying to structure a part of my games "style" to have async functionality to perform stylistic behavior and i want these features to be indipentant from the actual game loop.
my question is, is there a way to make sure the regular game logic isn't affected by the async function/s?
you need to be a bit more specific
give an example maybe of what youre trying to do
lets keep it simple. so imagine the only game loop thing is just a timer that always needs to be updated regularly. now for the example of the async functionality, clicking the mouse button will begin to trigger async await functions.. lets say 3 seperate, one following the other after completion ( time based ). now how do i ensure that the game clock isn't awaiting the other async functions but only the async functions listen to eachother?
so you want the clock to wait for the task to complete and that task will start another task
how do i prevent the clock from 'stopping' during a async function in the background
no. exactly the opposite
you want the clock to not wait for the task to complete but wait for the task that the first one starts?
give me 1 min. i'll restructure my question for you with better organization.
@spare island
Game loop: constant clock ticking up, and never stops for anything.
OnMouseClick : asyncFunc1 => asyncFunc2 => asyncFunc3;
during mouseclick async functions, game clock is still up-ticking reguardless of async functions executing or not.
^^^ this is the functionality i want. how do i make sure this never fails
why would the clock stop
idk, maybe if the game loop becomes more "intertwined" with complexity, it might start affecting some of the game loop functionality since the game loop is indirectly tied to all user behavior. my question is how do i make sure that the async functions never stop game loop functions but only stylistic functions.
are you sure you're not wanting to use coroutines?
you make a good point, i guess i'll redirect my question: can i make sure my async functions behave similarly to coroutines?
the reason i don't want to use coroutines is because i will have to chain complex functions together depending on the situation, and async is just a much better option for that.
The whole point of async is to not ‚block‘ the other stuff in the game
yep
the problem with async is that it doesn't play well with the unity event loop
Unless you do heavy lifting in those tasks nothing will block
Why do you say that?
yes this is what i'm talking about, the unity event loop sometimes seems to hiccup rarely. idk why. i figured it was because of async, because it's never happened with coroutines
i can't describe exactly why but some things just dont work with async
like debug.logs tend to be completely skipped
You’re probably using it wrong then
those 'some things' are what i want to fix, without using coroutines. is there a way with async
i'm using it correctly
You can still log stuff from async tasks if you make a workaround. So technically yes, it doesn't work, but also yes, it can work.
This is so unspecific that there is no way to tell you how to fix ‚those things‘
i thought the reason for async is to block presiscly? lol i will only choose async if i want specific things to be blocked temporarily until it's told to do so.
by debug logs do you mean exceptions?
no i mean debug logs
I have never seen them be skipped in an async method
i had an issue a while ago where i was trying to debug some async functions and for some reason they just never printed
but i found out later that the method was being run the whole time
just the logs weren't printing
this has happened to me as well
glad to know im not crazy
I smell async void
Depends if the async method works on the main thread. For example it works fine for Coroutines.
You can also use Debug.Log off the main thread iirc
you can
is there a way to specify which threads to use?
within the block of code
im wondering if thats what happened
i was way less experienced when i had those issues
why would you ever use async void? whats a good example
I'd guess you had debug logs (threadsafe) trying to log stuff only available on main thread, which would throw an exception. And if it's in an async void where you aren't catching those exceptions, it would just look like the method didn't work until you removed the logging
probably it
i wonder how many times i used async void
lol
If it's true, then they probably fixed it. I remember it wasn't working when I coded asynchronous communication between the firebase and the app.
async void is likely not a problem, it's not awaiting a Task that is
alight guys/girls. goodnight. thanks for the help
You know that all these return no handle that unity or the c# runtime can use to terminate or catch exceptions with so they may run forever unless the process is killed?
nope
should they all be tasks
You really should be using a cancellation token in almost every async method
and passing the destroyCancellationToken to it at the very least
Yes, or at least they should have a try/catch inside that kills them on exceptions and cancellations
The exceptions in async void will be captured by Unity—unlike what happens in other .NET applications. It's a fine way to do fire and forget.
Best is to never use void
im getting mixed messages
wait so when an exception happens inside of an async function it never gets collected?
Example();
...
async void Example() {
await Task.Yield();
throw new Exception("Example");
}```
what you need to be worried about is any case where you fail to await a Task
if you do that, then no exceptions will be printed to the console
oh so thats why i was always wrapping everything in try catches
well not everything but the async stuff im running
and Anniki is right that any async function will continue to run and unlike coroutines will escape play mode if you don't stop/cancel them
You only need to do that for un-awaited async
yeah ive noticed that issue before
i've been manually adding a check to see if the app is still running and stopping the task if it isnt
you should use the destroyCancellationToken
and just generally learn how cancellation tokens work
You may also want to have a look at UniTask which adds a lot of convenience (light Rx, eliminating/wrapping void, timing control, inline thread switching and non-allocating niceness to some situations among other things)
would it work to use a Task instead?
i'm just wondering because i'm going to have to change every time i used async void
and im going to have to learn what a cancellation token is and how to use it
If you use unitask you can wrap all void in a safe handler
im importing it atm
im a bit confused of how to use a cancellationtoken still
for example with LobbyService there is no cancellationtoken argument
I guess i dont understand how im meant to use it fully even looking at the examples
Lobby lobby = await LobbyService.Instance.JoinLobbyByIdAsync(ID);
What the heck? What does -0 mean?
null means null
Touche
the joys of computer math, zero can be positive or negative
just like any other number
no not at all
And comparisons?
float comparisons should never be for equality anyway, so as long as you dont do that you're ok
Yeah, currently only using < for this variable
Make a token source, pass its token into any awaited/async task that supports cancellation. Call cancel on the source when you want to kill the tasks that have the token
wait how would i use multiple cancellation tokens though
To support cancellation you typically have to go nothing more but in complex functions or where a task you are awaiting doesn’t support cancellation you check the token manually and throw or return when cancellation is requested
Create a cancellation token union source
That allows you to combine tokens
so like put it in a while loop?
you should however keep your token sources few
well since i hav ethe power to do so now i'd like to have a timeout for joining a lobby
i'd need a second cancel source for that
Yes, but typically you will put it on something like Unitask.Wait which supports cancellation throws
The cancel exception then breaks out of the task
depends where you put the timeout. It could be inside the task and use the same cancellation token you have passed into the outter task and respond to it with further internal cancellation/handling
Lobby lobby;
lobby = await LobbyService.Instance.JoinLobbyByIdAsync(ID);
SetLobby(lobby);
so for this how would i wrap this await to wait for it to be done?
Does that api not support cancellation/timeout?
theres no parameter for a cancellationtoken
What’s does it return?
Task<Unity.Services.Lobbies.Models.Lobby>
something like that
can i just put it in a while loop and check its status
right so cant i just put a while loop to wait until the Status is equal to 'RanToCompletion'
The api supports an options struct
i believe thats for passing things like a password to join but i can check rq
Yes, nvm
Task<Lobby> task = LobbyService.Instance.GetLobbyAsync(ID);
while (task.IsCompleted == false)
{
if (this.GetCancellationTokenOnDestroy().IsCancellationRequested)
{
throw new OperationCanceledException();
}
await Task.Yield();
}
if (task.Result != null)
{
SetLobby(task.Result);
}
it looks like it would work but it also looks stupid
Agreed, it also won’t stop a runaway task
Sounds terrible
and then this guy came to the conclusion you did
Unitys async APIs aren’t the grandest
im guessing the lobby service must handle cancellation itself
Async in unity suffers a lot by loads of legacy event based APIs and defaults to using coroutines. This makes code very ugly
Unitask aims to smooth over those
Ofc not, unitask is generic and can’t fix bad APIs just incomplete ones
its like im watching history repeat itself
as i go through this year old thread
doesn't seem like theres an official solution to it
There is a chance that the api is designed in a way that cancels are unnecessary or undesirable
i dont currently have any strange behavior happening that i think i can attribute to runaway tasks
the game does basically collapse if i load a scene in the wrong order but i think thats just because of how i have it set up
very stronk code
timeouts are built in
i know that
maybe because of the way lobby works its not even possible to cancel it once the request is sent
and ill probably prefer using coroutines to just avoid the mess of async altogether
A coroutine wont change the issue though
using them in situations where i can to avoid having to make sure they get destroyed
and like some people said in this thread, im a bit uncomfortable of the idea of trusting this library
at least in terms of support
i will probably go and convert the voids to Unitasks though
Good morning everyone, or whatever time it is for you. I created a third person camera script. The rotation works fine, so my next step was implementing camera colission. For that, I used a RayCast that shoots forward out of the camera to the player and checks if there is an object inbewtween. But the RayCast only returns true if there is a whole object in its path. As you can see in the video I added for further clearance, the camera colission works on the thin wall, while working not working on the big cube. I was wondering if there is an alternative to RayCasting that has the same or similar approach. I know CheckSphere etc exist, but there isn't a version that works like RayCast.
What concerns are those?
RayCast only returns true if there is a whole object in its path
The raycast isnt detecting objects that it spawns inside of. You might be able to get around that by temporarily setting this https://docs.unity3d.com/ScriptReference/Physics-queriesHitBackfaces.html buuuut id really just use cinemachine which has everything you're making already built in
mostly future support and reliability
third party repos like this on github are liable to just stop being updated
it is open source which reduces that risk a bit but its still there
Do I have to set that Bool true in some kind of game settings or is it enough if I set it true in my script? I set it true in Start() and it doesn't work.
Camera collision is built in to cinemachine
Yes I know, but I really would prefer to have done that by myself.
dont think theres an option for this in the physics settings. You also wouldnt want to just change this setting purely for the sake of the camera, as this affects all physics queries. So you could change it back after doing the cast but still, cinemachine already exists. You could also look into what cinemachine does if for some reason you wanna not use it
good camera movement really isnt easy, just use it. You'll take weeks longer to create something worse than what already exists, with less options and potential bugs.
'dont re-invent the wheel'
Well, you've convinced me. After implementing Cinemachine it's working as it should.
Have laggy scroll. With fast short swipes
and you are posting in a code channel, why? #📱┃mobile
To get ready to use solution
hey guys, when i switch my unity editor version i always get this message and i normally press yes but then i start getting gradle build errors when im trying to build, so is there anything i should do ? or is there a fix ?
Look into who actually sponsors this repo, this isn’t just a random git repo. Otherwise that’s ofc true. However any software can stop being supported at any moment, including internal ones 🫨 https://www.cygames.co.jp/en/
I'm not too fond of the "dont re-invent the wheel" thesis as we do learn quite a lot by re-implementing stuff ourselves
Though yes, it will take a bit more time than if one was to import everything
I mean, going even further in the reasoning, why make games in the first place if similar games already exist
because we like doing
making the stuff
learning about it
having meaning in life through hardship
so yes, do re-invent the wheel
But again, it depends what one cares about
I would echo that, know how to do it yourself, then use a library if it fits the use case, at least that way you will know how to fix it when it goes bang
yes exactly
and also it makes you aware of functionalities you didn't even know about sometimes
like "oh it does that too?"
indeed
maybe if it aint broke don't fix it may apply better
well, that's more of a 9 to 5 dealing with legacy code kind of mindset I think lol
But in this case, we are working on greenfields (?)
maybe not ofc
all of unity is legacy code 😭
honestly a miracle of engineering it works
more luck than judgement methinks
seeing as unity barely has an internal game dev team i'd say its probably luck
though last time, when I was working on a ParticleSystem, I was really surprised to learn about how you could initialize a variable with a property of the ParticleSystem, and that the initialized variable would "basically" be passed "by reference" (exactly but it's the idea) instead of by value as all variables typically are in C# (?)
no, the problem is they dont have an app dev team and never have had
they had one didn't htey?
nope
what about Gigaya
This isn’t actually the problem, most software companies operate that way and produce sometimes excellent results for users, they however care to observe users in the wild and aim to make a useful product instead of short term shareholder value
yknow, the "triple A quality sample game" they were making https://www.youtube.com/watch?v=-S6J8zm_w1E
*UPDATE: Production of Gigaya has been discontinued. There are currently no active plans to publish it, but it will remain as an internal resource at Unity. We want to thank you for your support and excitement for this project. You can find more information on our forums and feel free to ask any related questions there, we will do our best to an...
and then abruptly cancelled like a year later because they found working in unity too difficult
A demo team is pointless for informing anything outside basic UX improvements
sorry it didn't even last FOUR MONTHS
Thats a game. Im talking about application development like specifically the Hub and the Editor
ngl unity could use UX improvements
Well, depending on your expectations you may think it’s even good enough
it’s not a DCC app like blender
You’re supposed to make the tools yourself in U
Try making any custom tooling in any other engine
unreal 
yall do you know if theres a way to prevent strings from being stored in globalmetadata with il2cpp enabled?
theres some sensitive strings that I wanna keep secret from being accessed
like what
lol
Make them in-sensitive
Whatever + a truckload of custom tooling
Either unreal or they pay for the fancy version of unity where you can modify the source
wdym
well they usually have to modify unreal too
