#archived-code-general
1 messages ยท Page 442 of 1
btw this is a #๐ปโcode-beginner . Here you're expected to know the basics of unity..
queries are like raycast, or overlapsphere etc.. there is nothing much to "overhaul"
Collider field should work just fine in inspector, how exactly do you plan on using that to help though ?
its working now, there was just an error I did not catch keeping it from updating. I'm sorry I did not realize this fell outside the real of general. Just a CpE taking a game dev elective.
It does not seem it will work since OnTrigger doe not keep track of which collider on the component was entered only that a collider on the component was entered.
The Collider is the component; do you mean GameObject? You should place collliders on separate GameObjects attached to your main GameObject . . .
Thanks yeah a few people have said this. Thankfully for my grade for today, i was able to assign a layer mask to it in the project settings. Which is a bit of a waste of a layer since there are only so many. but at least it works for its purpose today.
code should be posted using links ๐
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
A tool for sharing your source code with the world!
done
i wanted to know if maybe i can upgrade it and make cleaner
to make it cleaner you should split it into smaller methods, each method should perform a specific functions instead of being all crammed in Update .
Another thing you should probably do is apply rigidbody forces in FixedUpdate
also lerp can use some fixing but no biggie. https://unity.huh.how/lerp/wrong-lerp
thanks
ill apply these tips
Hi! Sorry if this is the wrong channel, I'm not quite sure where to put it. Iโm working on a Unity UI system where a shop item can be dragged and dropped onto a border collider to trigger an action. The drag works, but the trigger doesn't fire at all.
Iโm dragging a UI element (inside a Canvas) using IBeginDragHandler, IDragHandler, etc.
That element has:
Rigidbody2D (Dynamic)
CircleCollider2D
CanvasGroup
Script with OnTriggerEnter2D(Collider2D other)
The border collider it should trigger has:
BoxCollider2D (Is Trigger โ
)
Rigidbody2D (Dynamic)
Both objects are on Z = 0
I'm using Physics2D, not 3D
The dragged object is a child in a prefab, instantiated into the scene before dragging
The drag works, and the object moves correctly, but OnTriggerEnter2D never fires
I added debug logs โ nothing appears
This is the part that isn't working:
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log($"Triggered with: {other.gameObject.name}");
ShopManager.current.ShopButton_Click();
Color c = img.color;
c.a = 0f;
img.color = c;
}
hey I followed your instructions, it works amazing now! Thanks!
@sterile reef the end result!
Now I have to find a way to keep the shadows static....
sweet!
Not sure if I want the shadows anyway, oh welll...
Actually, I think I will tackle the shadow missing problem later
Light is such a pain to handle lol
instead of disabling the gameobject you can make a new layer WallHide and exclude it from your camera
by setting the layer of the gameobject to be hidden
though i dont know if that also takes away shadows
Interesting, lets see....
Nah, that did not work. Worth the try though
It seems I need to use the ShadowCaster layer trick
It didnt work but thanks
Canvas UI doesn't work with rigidbody, colliders or collisions. Those are for scene GameObjects . . .
I'm working on a multi-step (few steps at most) action system for a grid based TRPG.
At each step of the action I want different things, example:
1) highlight valid tiles
2) if tile is clicked, do something
3) show a menu for the attack action if attacking is possible (ends a unit's turn) or just end a unit's turn
The issue is:
I want to allow the user to undo as long as the unit's turn is not ended (while they're still in the action).
This undo "reverts" back to the previous state.
However, I'm not sure how to do that.
Right now this is my pseudo code:
/// <summary>
/// serves as a memory for the action's stack. Helps with chain and undoing
/// </summary>
private struct ActionState
{
public Action doAction { get; private set; }
public Action undoAction { get; private set; }
public ActionState(Action doAction, Action undoAction)
{
this.doAction = doAction;
this.undoAction = undoAction;
}
}
public override void TakeAction(GridPosition position, Action onMoveCompleteDelegate)
{
ActionStart(onMoveCompleteDelegate);
var initialState = new ActionState(() =>
{
//do
MoveUnitToPosition(CastingUnit, position, CastingUnit.GridPosition);
}, () =>
{
//undo, do the reverse of the Do lambda
MoveUnitToPosition(CastingUnit, CastingUnit.GridPosition, position);
});
// do the step and add it to the stack
initialState.doAction?.Invoke();
stateStack.Push(initialState);
//create another state and show a menu
PromptAfterMoveAction();
}
//called when the player presses the cancel button
public override bool CancelAction()
{
//if no states exist, assume canceled
if(stateStack.Count == 0) return true;
var state = stateStack.Pop();
state.undoAction?.Invoke();
//indicates that all steps have been canceled
return stateStack.Count == 0;
}
It works so far (early prototyping), but given that some of the logic involves UI (menus, highlighting grid tiles, etc), I'm not sure if this solution would bite me later.
I'm not looking for full-code solutions on here, I'm aware that this is specific to my design system, but what should I look into when dealing with such a mechanic?
Hello! I'm currently coding some interaction with unity's terrain using code and scripting api. (Heightmap, 2d float array specifically) I'm trying to get all points in the grid array thats between a min/max point given to the function as a float, and minus some area from their height. however, when doing this, i cannot get why my code, which is min inclusive, maxexclusive, creates a "grid square" that is so much smaller then the bounds that was passed, could anyone give me an opinion on what i did wrong? https://paste.ofcode.org/T2gaEzjbwhL2ahGBKYsKyh
I know that the grid array index is cell - 1, but then the cast means that every part is always the cell below where the area is. cell -1 (for index) then +1 (because i dont want to edit things outside the bounds) for min. for max, its exclusive, so i want it to be 1 above whereever the last index to change is. -1 for array index, and then +1 because i want to edit things right below max value.
Wow that's a nice code but try go harder I am getting my codes with this issues of yours
i didnt understand your sentance, do you mind trying to say it in a different way?
I would guess that the method to set uses texel size and not world size or some other scale issue. Is the min/max point correct then (its hard to see in your screenshot)?
in the screenshot, the green is the index min/max converted to world coords, then created into a bounds. the red is the bounds given (bounds being minx/z and max x/z). it depends on Heightmap texture size and terrain size.
does that green gizmo match the mesh change? again i cannot tell ๐
btw you can use Vector2Int if you wish and id use many args instead of a Tuple here
heres another screenshot, and i do use vector2int, once i convert the floats to ints.
that green matches the minx,miny, maxx , maxy calculated in GetMinMaxHeightIndexes
the red matches the area tuple given as an arg to the GetMinMaxHeightIndexes
the green SHOULD be the Minx/y closest to the minx/y of the area, and the maxx/y closest on the outside of the bounds.
new Bounds(minCellWorld + (maxCellWorld - minCellWorld)/2, (maxCellWorld - minCellWorld)/2)
here you half the size too?
and go ortho in scene view to make this not shit to look at plz
new bounds(center, extents), center being min + max - min /2
its size not extents?
ahh, dumb of me. thank you
you can make your life easier by making this a vec sooner and doing a vec/vec or vec * vec operations btw
also you can do (Vector2Int, Vector2Int) to do a tuple
Ahh, do it right after minusing the transform.position, thank you rob.
no prob
Well, fixed the issue, problem is im trying to do this with a big terrain, creating a smaller terrain with same detail makes my hoeing HIGHLY more accurate
Im setting up procedural room generation with prefab rooms, but i am currently try to avoid overlap with box colliders, but this currently just stops generating any room as it some how detects overlap
you'll have to share more info
What do you need
ill call and screenshare if you want
Procedural Generation Issues
if (Gamepad.current == null)
{
screenMouse = playerInput.UI.Point.ReadValue<Vector2>();
}
else
{
screenMouse = Mouse.current.position.ReadValue();
}
screenRay = Camera.main.ScreenPointToRay(screenMouse);
crosshairRect.transform.position = screenMouse;
timePlayed = Time.realtimeSinceStartup;
aimRig.weight = Mathf.Lerp(aimRig.weight, aimWeight, Time.deltaTime * aimSpeed);
can anyone help here? i got a virtual mouse script on my crosshair and i'd like to use the gamepad right stick to move that same crosshair, its working but thing is when i stop the stick motion it snaps back to the left screen corner
i might be overriding something
what's the type of screenMouse?
if it's vector3 or vector2, it defaults to 0,0 if unset
it can't be unset
yes
hence getting on the left bottom side, an easy way to fix this is to only call the logic:
crosshairRect.transform.position = screenMouse;
IF the cursor/gamepad actually moved.
IIRC, for Mouse, there is a "hasMouseMoved" method or something like that, returns a bool if it has moved or not. (If not, get the mouse delta and check that it is not 0,0)
I'm not sure about gamepad, you might need custom logic if such a method doesn't exist
if there is a gamepad, you use the mouse?
personally no, but sometimes it's good to support different input methods.
In disgaea 5 for example, I played it mostly via keyboard
However, when I'm eating/feeling lazy, I just play with mouse while using my other hand to eat or rest.
So I'm not questioning OP's logic, he just needs better handling
I know
no clue what you're trying to say then lmao
its Vector3
if gamepad is null
was testing to see if the problem was using the same input
still snapped
personally i always prefer single player games using gamepad, unless they're UI heavy
look at your code again
if Gamepad.current is null, you read playerInput.UI.Point
if it isn't, aka there is a gamepad, you read Mouse.current.position
ah thats old code
sorry
was looking at a more recent version on my screen
if (Gamepad.current == null)
{
screenMouse = playerInput.UI.Point.ReadValue<Vector2>();
} else
{
screenMouse = playerInput.Gamepad.Pointer.ReadValue<Vector2>();
}
was looking at this
gotcha
i also checked unity's virtualMouse script and found a function they use to update the motion
if (Mathf.Approximately(0, stickValue.x) && Mathf.Approximately(0, stickValue.y))
{
// Motion has stopped.
m_LastTime = default;
m_LastStickValue = default;
}
else
{
var currentTime = InputState.currentTime;
if (Mathf.Approximately(0, m_LastStickValue.x) && Mathf.Approximately(0, m_LastStickValue.y))
{
// Motion has started.
m_LastTime = currentTime;
}
i thought the problem was that m_LastTime = default
tried commenting that code but its still snapping
have you tried debugging the values you get from that?
are you sure it can read directly as a pointer?
its reading as a single value
...no clue what you mean by that
if (Mathf.Approximately(0, stickValue.x) && Mathf.Approximately(0, stickValue.y))
{
// Motion has stopped.
m_LastTime = default;
m_LastStickValue = default;
Debug.Log(m_LastTime);
}
else
{
var currentTime = InputState.currentTime;
if (Mathf.Approximately(0, m_LastStickValue.x) && Mathf.Approximately(0, m_LastStickValue.y))
{
// Motion has started.
m_LastTime = currentTime;
Debug.Log(currentTime);
}
i mean this
why are you debugging the time
oh i wasn't specific when i said to debug "the values", sorry
i mean the values here
oh xd
mouse values
gamepad values
maybe best way really is to just have a boolean check if the stick is moving
yeah this seems like a delta, not a position
using UnityEngine;
[System.Serializable]
public class Connection
{
public Node from; //The node where the connection starts
public Node to; //The node where the connection ends
public bool bidirectional;
public float weight;
public Connection(Node from, Node to, bool bidirectional)
{
this.from = from;
this.to = to;
this.bidirectional = bidirectional;
this.weight = Vector3.Distance(from.position, to.position);
}
public Connection(Node from, Node to, float weight)
{
this.from = from;
this.to = to;
this.weight = weight;
this.weight = Vector3.Distance(from.position, to.position);
}
}```
This is a Connection Class, there is also a Node class that has a Connection list in it, the issue with the Connection list within the Node class is that it causes infinite nesting, which severely damages performance in unity, how could I avoid this infinite Connection nesting?
how do i make a raycast ignore all collisions except two types of objects/layers?
you can use a layermask.
the structure isn't an issue in itself, at least one of them is a ref type
are you traversing the structure recursively or something? if so you could keep a "visited" set/list to make sure you don't backtrack
they also have different layermasks, basically i want to make an enemy that doesnt notice the player if there's another enemy standing between them, but in doing so and setting the layermask to enemy it's detecting itself as they are all copies
make the raycast start a little outside the enemy shooting it
if you want that behaviour it would not make sense to use a layermask then.
you could simply use a CompareTag and see if it hits the enemy or player
then you would have to do what Chris recommended so that your rc is outside of your own collider
this should do the trick.
why is this happening
Kinda hard to tell without knowing what your Ship script is doing
its just rotating the ship gameobject
it has children with rigidbodys, no gravity
and im testing now and its like the velocity is not local
If you change the transforms of a parent, the children will be affected
how do i get the velocity to also be local?
Dynamic rigidbodies don't really go well with parent/child relationships
since they are simulated through physics
oh
it would work that way but the problem is that I have a lot of colliders on my 2d scene, and i need the Raycast/Linecast to ignore those and keep going until it meets either another enemy or the player. Some of these colliders also have their own layermasks ;/
That's what the layermask is for. You tell the raycast to test against colliders that are included in the layer(s). Then you can filter anything you want. If the enemy casting the ray is hitting itself, then move the raycast start position so that it isnt inside the source
Alternatively you can use raycastall which doesnt stop when it hits something, but instead returns everything it hits, then you can check what it hit and filter as you need there. A standard raycast is cleaner though, if you can make it work where it doesnt hit the source caster
yes this solution is working much better thanks, the problem wasnt that it was hitting itself itsthat there's a lot of colliders in the scene it can hit that i dont want it to, so getting them all and filtering it until and if it finds an enemy is the way to go for me
Then supplying only the Player and Enemy layermask to the raycast should do the trick
how do i do both of them, I can see that i can feed it an int that would serve as the number of the layermask, how would i be able to give it both numbers?
You can create a serialized field for example:
public LayerMask hitLayer;
then in the inspector it will show as a dropdown where you can select multiple things
then in the raycast you feed it the hitLayer where it asks for the layermask
ive tried that but couldnt get it to work, where would I dynamically change the layermask?
i previously put it inside where it would detect that it hit said layer
It's something that is usually predetermined. For example if I have a script for an enemy that performs an attack, I have the serialized field already set inside the class
then in inspector I would assign which layers this attack should be able to hit
the int is the value of the layermask
a layermask is just a bitfield/bitmask wrapped inside a pretty struct
yes, the order of the layermasks no?
Think of it as a whitelist you give the raycast
a layermask of 0 means nothing
a layermask of 1 means layer 0
a layermask of 2 means layer 1
a layermask of 3 means layer 0, 1
a layermask of 4 means layer 2
no
i think you're confusing 2 terms, you're calling "layers" and "layermasks" both as "layermasks"
ah, it doesnt start at zero
it doesn't start at any value
it just is a value
or you could view it as being many values
A bitmask is a representation of many states as a single value.
It's easier to just think of it as a list of Layers
the raycast checks all colliders with the layers included in the mask
wdym you couldn't get it to work, getting the dropdown?
wait a minute, so because the raycast is always aimed at the player, if i simply check to make sure that there isnt an enemy in the way, then that would work?
Yes that could also work
It depends what you use it for
If you need to know where you hit the player you would still need to include the player
that'd work yeah
no i wouldnt need that
so i can just set the layermask to enemy and that should work? i think i just complicated this for myself for no reason ๐ญ
Yes
anything you put in the layermask, is what the raycast will do hit detection for
yes i think i overcomplicated it by thinking i needed to detect the player when its already aimed at the player and can simply do a function somewhere else if raycast doesnt detect an obstacle, of which it would only be an enemy
however this layermask thing is hard to grasp, how does this sequence work?
youre right i dod confuse layers with layermasks
what layermask would i need to use to get the 6th layer which would be the Enemy Layer
or is it something completely different
It's easier to just to make a public or serialized layermask variable ๐
then you have a nice UI where you select which ones it should be, and the nice magic works out the bit shifting for u
did you check out #archived-code-general message
6th, or layer 6?
Feel free, I almost never need to know the nitty gritty for what I've used raycasts for, but it can be very efficient in general for flags and other things
the former would be 128, the latter would be 64
but really you should just use the inspector UI to set it, much easier
it's just making a serialized field that's of type LayerMask lol
its just hard to grasp for me ๐ญ
its the layer number 6
so... layermask 64?
should I just write 64 then? its not like ill shuffle my layers around any time soon
did you check out the link i posted
no i didnt lemme scroll up
no, you should check the box labelled "Enemy" when you configure the layermask from the inspector
....we've been telling you to do that the entire time tho?
from way up here lol #archived-code-general message
i have problems understanding things at times
;/
yep, works like a dream, thanks guys 
cant believe i kind of had it at one point and deleted it all before coming here smh my head
How to hide game objects in a generic way, similar to how when you press the eye button in the inspector?
Is it important that they're not disabled entirely? Just hidden visually?
Yes.
Will need to disable the renderers then
Also I want it to work in the editor: how when you press the eye symbol.
My controls don't have the renderer components, they're OnScreenControls.
Well, I guess they're images specifically.
Also when I press on the eye in the editor, it doesn't seem to disable the images either but everything is not visible.
So on a canvas?
Yes, but not necessarily, I guess.
Add a canvasgroup, make it transparent
Quick question about GLTFast - the documentation is creating a new GltfImport every time a file is loaded, but doesn't seem to use it after the .Load call. Is that necessary or can I re-use the same one if I have to load multiples? The documentation isn't clear either way - it just does them in every section, presumably to make each piece a self-contained snippet of code.
https://docs.unity3d.com/Packages/com.unity.cloud.gltfast@5.2/manual/ImportRuntime.html
Guess I'll just have to
, but for that I need to actually get it to run multiple imports.
Previously, I was doing this with a Coroutine, but Gltfast is expecting async, and I'm not entirely sure how to "kick off" an async. I get the general concept of it, and I've used it before with async Start and the like, but this one needs to fire when a variable changes (a string representing a directory full of GLTF assets to scan through) which is done in the UI. I have the event and everything all wired up, the user picks a directory and it goes to an ordinary function OnPathChanged, which used to use StartCoroutine to kick off an IEnumerator that loaded the assets one at a time. But now that LoadMeshes function is an async Awaitable LoadMeshes instead. How do I kickstart an async outside of another async?
you just call it and you can await it (as it returns a task) or do nothing or use .ContinueWith() to execute a delegate when it finishes instead.
I can't await it since the function that calls it isn't async, and I don't think I can call an async from a UnityEvent
you surely can
async is not like a coroutine where it needs special handling to make the yielding work
I don't need this function to do anything after starting the task, I just need it to fart in an elevator on its way out. The task will start loading in the meshes as it goes and fire off events, isn't there a way I can have synchronous code just, queue and abandon an async?
public async UniTask MyCoolAsyncFunc()
{
await UniTask.Delay(100);
Debug.Log("foo");
}
MyCoolAsyncFunc();
//do other stuff
ha got there in the end
MyCoolAsyncFunc().ContinueWith(() => Debug.Log("I get called after this is done"));
So, this warning can just be ignored? If I don't care about the results of this function I can just call it like this?
yes
If you use UniTask you can use .Forget() to make it shut up and log exceptions correctly
You may notice that if it throws an exception it wont be logged until you stop playing.
Unity are dumb and added Awaitable too late hence many of their packages use Task when you should not use it in your own code
I use UniTask in projects I work in
Does UniTask work with await Task.WhenAll?
It has its own version
Okay, I'll see about getting that
Also has helper functions such as:
someUnityEvent.AddListener(UniTask.UnityAction(async () => {}));
But as it currently is, Awaitable seems to not be doing anything. I'm gonna do some debugger time and see if that's my fault in the function itself or if it's just not starting the task
avoid doing _ = AsyncThing(); and do AsyncThing().Forget() and also debug to see whats up
Okay, it seems at some point in my thread, an exception just gets lost to The Void
I was clicking through it and my entire debugger context just vorped into nothing
I'll go get UniTask
Exceptions in other threads never get logged to the unity console so you want to debug + enable break on exceptions.
Or use the UniTask functions to run code elsewhere OR catch it fully and log them yourself.
Yeah, I've stepped on that particular rake before so I knew what to expect when it just silently died. I just kinda need the error to know what went wrong
So I'm gonna try out this UniTask thing
I have a TaskScheduler.FromCurrentSynchronizationContext() that uses the System.Threading namespace, can I just keep that or is there a UniTask equivalent?
I just spent 40 lines of code on an ADS script and i was just told about ternary operators
Apparently i could do it in like 10 lines
What the fxck
Fewer lines is not always better
I know, i know
UniTask should be using the unity task scheduler already but they use their own things also using the update loop.
But it still bugs me how easy it could've been instead of me overcomplicating everything
I also learned about coroutines today :>
Probably the most useful thing i've encountered in a while
It's the GLTFast importer, it uses ContinueWith and passes TaskScheduler.FromCurrentSynchronizationContext() as the state to it.
Ah, you can use .ToUniTask() and then continue with and not worry
Or in the continue with you can use await UniTask.SwitchToMainThread();
Is that an extension method somewhere I need to get? It doesn't recognize that function.
the delegate can be async.
Actually im not 100% on if unitask will use the unity scheduler automatically ๐ค
Hmm I presumed it was a thing but perhaps no. Id leave the sync context arg then like they have or go back to the main thread like I said above ^
tis a pain managing this sometimes
Ha guess there is one
Yay progress
Okay, found the source of the error
Turns out the answer to this one is "No, make a new one every time"
Okay, good news: Async stuff works like a dream, got all the meshes streaming in just as I'd expect.
Bad news: For some reason every east/west facing wall has been infected with a poultergeist
Almost certainly something wrong with my import settings from gltfast, kind of looks like mipmaps gone haywire? Maybe shadows?
It's the Triplanar shader I wrote 
No idea why it worked with the TriLib imported mesh but not Gltfast but it certainly does seem to be a me problem, guess I have to go figure it out
Seen similiar stuff when a mesh is missing tangents
Maybe TriLib did some sort of auto-correcting? Messing up my tangent math when generating these meshes is certainly within the wheelhouse of "Shit, I would do that wouldn't I?" and I've just never noticed?
Would explain also why it happens only on walls in a very specific orientation
How would I compute the tangents of a triangle, given the vertices and normals?
Looks like I need the Cross Product of the normal and world up?
So now I need to actually learn how to do a Cross Product because my mesh source does not have a convenient Vector3.Cross method
Mesh has functions to do this
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Mesh.RecalculateTangents.html
If you can get it after loading that is
I probably could, but I think GetComponenting the mesh filter and pulling the mesh from it would be a significant drain on resources
but maybe there's somewhere further down the pipeline where I do have access to the mesh that I can do? A few frames of static is acceptable if it "pops in" later
Why? It's already a mesh on cpu side and seems like you need to fix this
Success! I found somewhere later on in the processing chain that got the mesh filter and just slapped a RecalculateNormals function there and no more static
The issue was the GetComponent. There's a lot of meshes, and an extra GetComponent call would have noticeably slowed down loading, so I wanted to find somewhere else to handle that instead of at load
No, it's like, thousands. And GLTFast gives me the whole instantiated objects, not the meshes themselves
A Java program I also maintain so I definitely borked the math on it
Probably the normals are bad? I forget if tangents are calculated or are imported
The normals seem fine, problems with those would be visible in the lighting. It's definitely my math because I'm forced to work in a really janky psuedo-vector data structure that sucks and has zero convenience functions
anyone here know how linearDamping applies to a rigidbody, like when calculating the resultant force how does it affect that equation
there's a formula on the 2d version's docs
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D-linearDamping.html
not sure if this also applies to the 3d version but it probably does
hey thanks
So, now that I've got this fancy UniTask library, is there a way I could use it to queue up multiple functions, and run as many of them per frame as it can while keeping up a certain framerate? I have a bunch of stuff that uses AddComponents and other UnityEngine functions, so I can't offload it to another thread. Still, I'd like to make sure the framerate stays as close to 30 while loading them as possible. In a Coroutine, I'd keep a running tally of how long it's taken to execute each function and yield return null when that timer goes over 33ms. Is there a better way to achieve this with UniTask?
well you could replicate the behaviour by awaiting the next frame via await UniTask.Yield();
Yeah, but I was wondering if there was some fancy way to queue up a bunch of synchronous functions like UniTask.RunOnThreadPool
Which would be perfect if I could multithread these
well you can delay for an amount of frames so technically you could yourself "queue" up work over many frames at once
Yeah but the amount of time they take isn't always static
some of the calls have to do a lot more heavy lifting than others
"Run as many of this as possible without dipping below X framerate" seemed like a common enough use case that I thought UniTask might have a system for doing so other than Stopwatches and Yields
Its probably an over step(for UniTask to provide this) but you can surely make your own utility to run a set of Func<UniTask> and wait till another frame between if some time limit is reached.
Are you doing something that must be done on main thread? Because otherwise you could just put everything in a background thread and let it run as long as needed.
Yes, lots of Unity functions like AddComponents
Yeah I don't think there's something built in, but you could make a method that returns Time.realtimeSinceStartup - Time.unscaledTime > budget ? UniTask.NextFrame() : UniTask.CompletedTask.
I wouldn't do it this way but as I suggested if you wish to avoid placing checks everywhere
Basically, I wrapped the expensive-ass function in this:
Stopwatch timer = new Stopwatch();
timer.Start();
long currentTime = 0;
foreach(...){
long startMills = timer.ElapsedMilliseconds;
ExpensiveAssFunction();
long endMills = timer.ElapsedMilliseconds;
currentTime += (endMills - startMills);
if (currentTime > 33)
{
await UniTask.Yield();
currentTime = 0;
}
}
I'll un-magic that number if this works
Giving a list of functions is basically just abstracting on top of it, so instead of manually placing checks, you manually split it into multiple functions, it's not much different.
It's actually worse if you need to pass values from one function to the next.
Yeah with a method wrapped up like above, you could just do something like:
foreach (...)
{
// Some expensive work
await NextFrameIfOver(0.033f);
}
(Well, depends on how you want the budget to be counted)
Can someone help me in #๐ปโcode-beginner
I got a Big issue and i cant find the problem ๐
Well they kinda wanted it to be automatic so do you
You have to manually decide where is an acceptable place to break into next frame, no matter the approach.
That's certainly more automatic than what I have
The difference is just "where do I manually insert await NextFrameIfOver(budget)" vs "where do I manually split this function into multiple parts."
I hadn't thought of just using unscaledTime as the benchmark... that's a good idea. Lemme give that shot
don't crosspost next time. Stay in 1 channel
one slightly more automatic way i've done this in the past is writing the method in question as a coroutine, then instead of running it directly, make a wrapper method that takes an IEnumerator and iterates through it step by step and waits as necessary between steps. it's not much more automatic than the above, but it means you don't have to actually put any timing specific code in with the real work, just yield return null and let the wrapper method decide what to do, so it's really easy to do things like vary the rate or do other stuff between steps
I'm trying to set the color of specific sections of text in a TextMeshProUGUI component using scripts, but I'm struggling to get it working. The most I've been able to do is change the color of the text's underline.
You don't need to do anything as drastic as manipulating vertex colors
You can use Rich Text tags: https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/manual/RichTextColor.html
that's what I resorted to when <color=#FFFF00> didn't work
It should work fine ๐ค
like I said, it only changes the underline
maybe an issue with your font or something? ๐ค
What if you do it on text that isn't underlined?
does it work then?
nothing then
What if you switch fonts
but, the colors do change if I mess with the vertex color
it's gotta be this font, or one very similar
Sure but
just for the sake of figuring out the problem
an you try the default font for example
If that also doesn't work then we can at least rule out the font as the issue.
issue persists it seems
Strange. I've never had an issue with this ๐ค
What if you try to change the order of the nesting of the tags?
For example instead of <color><u>text try <u><color>text
Have you tried 8 characters
aalso a good idea^
That might make sense
Be careful with adding. That's a nasty, expensive method . . .
So you can change the colour of only the underline
Yep, that's why I want to run them sequentially instead of all at once, but I can't put them on different threads
silly question what if you try this in a separate completely empty scene
Just put a TMP_Text in it alone and play with the font and tags
delete all other objects
Also make sure to look at it in Game View not just scene view
oh wait I think I figured it out, Override Tags was enabled
it's supposed to work either way I think
yeh there we go
Ahh - I forgot about that checkbox
I do think that might be a bug though - the fact that it was coloring only the underline
Follow up question:
This text is inside a scroll box, I wanna have it set up so that the box automatically scrolls to the section of the text that's highlighted whenever it's enabled. How would I do that?
would it be possible to grab position values from the vertex index of a character or something similar?
Yeah, different threads wouldn't work. Do you have to use AddComponent? Are you able to place the component on the GameObject and enable it?
Yes, they're components that need to be there on a fully runtime-initialized gameObject loaded from a mesh in a different directory. Not every component is going to be on every mesh, there's no way around having AddComponents
Hmm split lines, iterate until you see colour tag then lineheight * line number?
You can get text info about the whole thing and set the relative scroll pos but finding where the text is im not sure ๐ค
line heights are kinda random cuz of the text wrapping
No can do then with this setup I think
Not easily at least
Why not make each conversation line separate and spawn them all in when needed
because 50 gameobjects being instantiated into a single text box will lag my quest 3 lol
Then you can reuse the same ones
No need to create and destroy gos yeah ur right tbh
I tried that with a different thing in my scene, an ingame debug output view with 100 components
Ouch, that seems difficult . . .
it was responsible for like half of all of my performance issues lmao
Not sure about TMP, but UGUI text has a TextGenerator, you can use that to grab all the positions of characters and lines.
If performance is that tight that you canโt handle 20 gos for 20 bits of ui text then idk
I am using a TextMeshProUGUI component
Is it necessary to have the entire conversation at once?
nope, it's already split into pages
A solution if itโs ok is to just split up the conversation
More
Important highlighted text could even be its own conversation turn
Makes sense if itโs important
with a max line count of 50 I'm already getting 32 pages of text in some places lol
From a player standpoint itโs a bit of a flash bang to get all this text
At once
More easily engagable if itโs a few lines max at a time
VN style
this is less of a game and more of a data science app so the text is the content inherently
I wonder if you use GetTextInfo() and use the character infos it provides? https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/api/TMPro.TMP_Text.html#TMPro_TMP_Text_GetTextInfo_System_String_
Not sure if topleft/topright is the character local pos: https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/api/TMPro.TMP_CharacterInfo.html#TMPro_TMP_CharacterInfo_topLeft
nothing has a description
Yes I just saw this on docs while looking through
At same time haha
If you like foreach var wordinfo
Check for the text you need
Then get first character position
Should work
Surprised that exists actually
yea you can loop until you get a match over a range of characters and then use the first to calculate the new scroll pos
yeah I think that's working, it seems to be localPos
gotta edit my code's logic a bit to actually get the correct character index but I'll try it
WordInfo.textcomponent.m_fontColor might be easiest
Thereโs like a gazillion properties in this TMP_Text class
Ah thereโs one thatโs just textcomponent.color
If you can insert your own tag and find that then that would be a clean solution
using colour seems bad
yes we know its coloured yellow but its not very reliable vs an exact string match or pre determined char index.
Lots more effort though
I wouldnโt be unhappy using color cause it takes 10s with the stipulation of you have to change to this method if you NEED to
Nevermind there is actually textcomponent.string
All the way at the bottom of this 300 entry properties list
Not surprised that mesh info is exposed especially since UGUI text also exposes it.
Though this might not contain the tags
I've always wished instead of some weird BBC custom format they use for rich text, they would just expose the internal AST.
There might not be any way to distinguish without using color or some other actual property of the text
Trying to sanitize user content by escaping the BBC tags is hacky and weird, and there are quite a few of Unity games that they just don't bother and you can use BBC tags to change your user name colors and what not.
oh shit you can get link info so you could use this to easily find the character positions for the headings
presuming these can be made to not change the text style
hmm.. I can't seem to figure out how to get the right character index
I'm currently doing it by just noting the length of the string one I find the line to highlight
but that apparently doesn't line up with the actual character indices in the textbox
seems like the string length is always longer than the length of the characterInfo array
it surely wont include the tags so the rendered characters len will be less than the input string...
I think string excludes the tags tho
The scripting docs said โstring to be displayedโ or something like that
i presumed they were checking the original but you can just loop till you hit a char info matching char 0 of some string and keep going till you get a full match
you just need to know the thing to find such as "foobar"
oh wait one of the characterInfo properties is lineNumber
๐ well
@stark scroll !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โข Collaboration & Jobs
Iโm getting a Box Collider from a GameObject on awake and I get this error :
ArgumentException: GetComponent requires that the requested component โBoxColliderโ derives from Mono
If anyone is getting a box collider show me how please.
Show your code first
Have you made a class called BoxCollider this looks otherwise ok to me
hello, im trying to set vsynccount to 2(every second v blank) to lock my game at 30 fps on console, but it caps to 60 fps instead
when i debug the setting it clearly shows that its 30 fps/every2ndvblank
can it be a problem with TV somehow?
Is the TV 120Hz?
Unfortunately I donโt think thereโs a way to reliably cap framerate in Unity while maintaining vsync
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
also, you're getting a runtime error?
nah i haven't. i'm using Entities which so i think getting and using GO physics isnt allowed.
i'm going to try to access the collider through ECS
Oh you mean you are using a EntitiesPhysics.BoxCollider ?
{
case NodeManager.EResult.POSITIONAL:
lResult.directory = lNode.Directory;
lResult.windowFromDirectory = lNode.WindowFromDirectory;
goto case NodeManager.EResult.NON_POSITIONAL;
case NodeManager.EResult.NON_POSITIONAL:
lOutput = lNode.AccessText;
lWaitingPrefix = Format(lNode.WarpingText, input);
break;
case NodeManager.EResult.EVENT:
lOutput = "Event sent successfully!";
break;
case NodeManager.EResult.MAIL:
lOutput = $"QuickMail received: {lNode.name}";
break;
case NodeManager.EResult.FAIL:
lNode = NodeManager.Instance.Current;
lOutput = lNode.KeywordFailText;
break;
}```*
Hello!
I haven't found a way other than "goto" (which I never had to use before) for putting code in a case, while keeping the behavior that we have by chaining 2 cases
Is there a better way? ๐ค
yeah but i just swapped it for 60hz oner and it still does not work
on ps console it works fine tho
seems like it's a special case here that's intended to explicitly mark fallthrough
https://stackoverflow.com/a/174223
never seen it before either lol
Oh so it seems like it is the way. Thank you for the help ๐๐ผ
And as I see it isn't even a true goto ๐ค That's interesting, and very smart of them as the usage is still very reminiscent of goto
an alternative with an if-else chain is possible, but it's up to you whether you consider this a "better" way lol
NodeManager.EResult result = NodeManager.Instance.TryRouteKeyword(input, out NodeInfo lNode);
if (result == NodeManager.EResult.POSITIONAL || result == NodeManager.EResult.NON_POSITIONAL) {
if (result == NodeManager.EResult.POSITIONAL) {
lResult.directory = lNode.Directory;
lResult.windowFromDirectory = lNode.WindowFromDirectory;
}
lOutput = lNode.AccessText;
lWaitingPrefix = Format(lNode.WarpingText, input);
} else if /* other cases */
Ye, for these kind of things I find the switch cases more readable
hello i have a super idea for video game but i don t know who insere this code so i give you the script and if you whant you insere this code a ok (sorry if i wartter not good )
ps i am make me help for chatgpt
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
โข Collaboration & Jobs
If you follow the guides on learn.unity.com I'm sure you can figure it out.
<@&502884371011731486> #archived-code-general message
virustotal behaviour gives dangerous outputs
!warn 1088531099845664878 do not post suspicious files. There's absolutely no reason to post code as an odt file.
If you're seen doing similar in future you will be removed from the server.
momi1769 has been warned.
Its possible you may have Application.targetFrameRate set above 30 or the Screen.resolution you are using may have a higher refresh rate
Application.targetFramerate is ignored when vsync is on
Hi!
Hello everyone, Iโll try to keep it brief.
Iโm currently working on a year-end project at my school and Iโm using the MultiplayerService for sessions. The problem is that the schoolโs internet connection is quite slow, so I canโt create sessions and I keep getting timed out (knowing that it works fine at home or using 4G).
I wanted to know if anyone here had any workaround solutions that could help me out? (aside from being on 4G all the time).
Thanks a lot!
Does it let you specify the timeout time?
how bad is the internet, can you check via https://fast.com ?
It doesn't look so bad at first glance, but the problem doesn't occur all the time, and in the evening when there are fewer people, it works without too much trouble.
My theory is that the client is trying to join the session when it hasn't been created
Since the function is in async
I don't have a lot of knowledge on the subject, so I don't have an overview, if someone can tell me the potential causes of this issues
I would show ur code in networking channel
From my experience in n4e the designs were such that that isnโt possible
Idk if n4go is much different but Iโd assume youโd want the same
I can show the networkhandler it is make by a friend
My bootstrap
And when i tried to connect on relaynetwork i receive all response but he doesn't found the joincode
Ah mb
Hello, with a friend we have a end of the year school project and we need to create a game, we have all the ideas but we have some trouble with our dash mechanic, it's working but not like we want, and we don't really know how to fix it, if somebody can help us we'll be thankful
You'll have to explain how it works now and how you want it to work, and show the !code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
Okay, i'm doing it
So basically, when we want to dash horizontally we just press Shift, and if we want to dash upwards we need to press Z, but we just want only one button to dash in every direction, sadly we cant find the solution
Here's the code (2 parts separated) : https://scriptbin.xyz/odixudatac.cs
Use Scriptbin to share your code with others quickly and easily.
if you aren't using w/s for anything you could use wasd to aim the dash as well
Yea we thought about that but we can't seem to find how to really do it like that
i mean do you have the dash mechanic itself done?
Input axes from wasd into a normalised vector
you would just dash in the direction specified by wasd
And check holding space to dash up
I have a little math problem and I'm having trouble solving it.
I have a character that must look up a target by rotating its neck (vertical and horizontal rotation). However necks has a limit and so I must to clamp it somehow.
I have this values:
- A
Vector3 baseDirectionwhich is the base direction of the head (the "forward" vector). - A
Vector3 targetDirectionwhich is the (unconstrained) direction towards the target. - A
float maxHorizontalwhich is the maximum number of degrees the head can rotate horizontally. - A
float maxUpwardwhich is the maximum number of degrees the head can rotate upwards. - A
float maxDownwardwhich is the maximum number of degrees the head can rotate downwards.
And I must to use this in order to get aVector3 newDirectionwhich is the (constrianed) direction towards the target in which the character won't break its neck .
But I don't know how to get that.
I was trying with:
Quaternion delta = Quaternion.FromToRotation(baseDirection, targetDirection);
Vector3 angles = delta.eulerAngles;
angles = Normalize(angles); // Convert range to [-180;180]
angles.y = math.clamp(angles.y, -maxUpward, aimingTargetMaximumHorizontalAngle);
angles.x = math.clamp(angles.x, -maxDownward, maxUpward);
Quaternion newDelta = Quaternion.Euler(angles);
Vector3 newDirection = newDelta * baseDirection;
But it doesn't work. I'm not sure how to solve this.
using UnityEngine;
public class RepositionPlayer : MonoBehaviour
{
//where the player should spawn
[SerializeField] GameObject player;
[SerializeField] GameObject repositionObject;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
if (player != null)
{
Reposition();
}
}
public void Reposition()
{
player.transform.position = repositionObject.transform.position;
}
}
why is this simple script not working on build but works on development?
Try debugging it in a development build
any runtime errors? im going to guess player becomes null
fixed
using System.Collections;
using UnityEngine;
public class RepositionPlayer : MonoBehaviour
{
//where the player should spawn
[SerializeField] GameObject player;
[SerializeField] GameObject repositionObject;
// Start is called once before the first execution of Update after the MonoBehaviour is created
IEnumerator Start()
{
yield return null;
player = GameObject.FindGameObjectWithTag("Player");
Reposition();
}
public void Reposition()
{
player.transform.position = repositionObject.transform.position;
}
}
why is player also serialized if you then find it by tag?
Finding by tag is un reliable and you should always prefer serialized fields of the needed component type when possible.
e.g. [SerializeField] Player player;
this repositionPlayer object is in every scene
its not manually referenced
hence the tag reference
Perhaps a static reference to the player should be preffered then or you can better integrate this into your scene loading logic (e.g load scene, get spawn pos, move player to spawn pos)
Finding by name/tag is fine when a beginner but not a good practice long term
what about a C# event?
well if you have the ability to invoke an event and have the player listen then yea do that.
I like to have a component in newly loaded scenes (e.g. for a level) that is used to facilitate initialisation and setup (e.g. has ref to start pos and is directly read and applied to the player in level load logic)
Just make sure you unsub monobehaviour functions from events when they get destroyed to prevent future issues
so you have a OnLoadManager kinda?
sets up everything nicely on every scene start
yea i do that already otherwise memory leak goes brr
Games I have worked on recently have a LevelLoadService (not mono) and a LevelInit and LevelController in the level scene. this is found by the service when the scene is loaded.
hm i might do that in future projects
this is my first proper project so its full of shitty practices
learned about C# events halfway through
events are great. UnityEvent exists also which lets you serialize subscriptions in the inspector (has a cost due to needing reflection to resolve at runtime)
i tried both but C# events just seem way more intuitive
and having to set up all events manually with UnityEvents just doesnt cut it for me
you can sub in code too but yea a c# event is preferred for code only stuff
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
Hello I'm working on VR game and encounter problem when I want to attach and detach object to another game object. When I detach game object (grab) the size will be smaller. does anyone know how to solve it?
public class OnCollisionTrash : MonoBehaviour
{
public Transform slotObject;
public GameObject attachedTrash;
private bool isAttached = false;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Trash") && !isAttached)
{
// Attach trash to slot
other.transform.SetParent(slotObject, true);
other.transform.position = slotObject.position;
// Optional: Stop movement
Rigidbody rb = other.GetComponent<Rigidbody>();
if (rb != null)
{
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
rb.isKinematic = true;
}
attachedTrash = other.gameObject;
isAttached = true;
}
}
public void DetachTrash(GameObject trashObject)
{
if (attachedTrash == trashObject)
{
// Detach from slot
trashObject.transform.SetParent(null);
Rigidbody rb = trashObject.GetComponent<Rigidbody>();
if (rb != null)
{
rb.isKinematic = false;
}
isAttached = false;
attachedTrash = null;
}
}
}
Fix your hierarchy so you don't have things that are scaled becoming the parents of other things
Okay I think I can help kindly dm for ideas and more
Is there any built in file picker in unity that isnโt the editor utility one?
Pretty sure you need to use a third party asset/package for that
Huh wild I really thought their would be something built in for that
Thanks for the answer!
I presume its not a thing because many platforms just wont have one that works the same as pc/mac/linux.
but in editor they know its gonna be one of 3 platforms so its easier to use the os provided one
https://github.com/keiwando/nativefileso
https://github.com/gkngkc/UnityStandaloneFileBrowser
There are options on github
This looks great Iโll probably go with using this
Hmm I guess thatโs fairโฆ but they have lots of other features that have to host separate code for each operating system, Iโd hope that they have at least something that tries to work
just so you know, there is a bug in that lib during builds (from unity 2023.3+ iirc)
https://github.com/gkngkc/UnityStandaloneFileBrowser/issues/145
the fix is posted in the issues tab on the github
Thanks for the heads up
Hi, is anyone familiar with making particle system with collision on? my cubic smoke kept clip through floors, it sometimes work and sometimes don't. I want to do a rocket landing smoke effect.
I did add rigidbody to my terrain tiles. Sometimes the particles worked some times it doesn't like in the video. Two of them worked but other two didn't. There are times that they all worked.
here are my particle collision settings. Not sure more information is needed.
Thanks
I'm trying to use EditorSceneManager.GetSceneByName to get the scene name while in editor. It works for one scene but not another.
I have 2 scenes, PrimaryScene and SecondaryScene.
PrimaryScene works when using that call, but SecondaryScene fails. They're both in the same directory
are they both added to the build?
you can search for the asset by name btw
oh my god EditorSceneManager only returns information if the scene is loaded in the hierarchy
that is so stupid, the whole point of using it is to get the scene name so I can load it into the hierarchy
so search for the asset and load it then with the editor scene manager
AssetDatabase.FindAssets("t:Scene MyCoolScene");
yeah that's gonna have to be how I do it
Are script-only stack traces supposed to work when logging in non-development builds? Up until recently I swear they did and were just missing line numbers. But now it's just the log message and no stack. I don't see any relevant changes in our project's code or packages, I've looked at all the build and player settings, I'm checking Application.Get/SetStackTraceLogType() at runtime. And it all looks fine. If I turn on full stacks, it works, but script-only just fails. What am I doing wrong? (Unity 2022.3.42f1, mono scripting back end, Windows build)
Is this for managed exceptions or for crashes?
so I'm really not sure what the heck is going on
it's for all uses of the Debug.Log* API
As it turns out, in other projects, I have scenes that are named PrimaryScene1, SecondaryScene3, SecondaryScene4, etc.
I have the correct name of the scene that I need defined in a scriptable object, but using AssetDatabase.FindAssets($"t:Scene {mySceneName}"); causes it to return the wrong scene--basically a total crapshoot if it finds the one I want or not.
well its gonna return all matches for the search so i guess its then up to you to find the correct one?
yeah actually, I'll just iterate them to match the string name I have. FindAssets returns an array of guids. Gotta get the actual asset
yea you can convert guid to asset path and then load with this
yep, got it working! Thank you!
Hi im having issues here but the scenes are in the build settings?
LoadingScreen != LoadingScene
names dont match ๐
now im asking this because ive been staring at these too long and my brains scrambled can u see which one is missmatches
the error states the scene name you used and this doesn't match any of the ones in the build settings list
read it again and think ๐
Oh so my script has it as loadingscreen but its mismatches everywhereelse?
Ahh i get it thanks im dumb dumb
Hey, I have these areas that I need the player and NPCs to be at certain time and if they're not in those areas at certain time they will receive a strike and after 3 strikes they're punished. So what's the proper way to communicate from the script that's on those areas (Box Collider with "Trigger" set to true) to the DailyRoutineManager that handles all aspect of checking if they were in those areas at the right time, punishing them, etc... ?
right now I have this :
DayNightCycle.cshandles the DayNight timer of 24 hours and it has an Action calledOnGameTimeChangedthat's called everytime the time changesDailyRoutineManager.csthat subscribes toOnGameTimeChangedto do all the checking about the players and NPCsOnAreaEnter.csthat's on those BoxCollision ( Trigger) that detects when those players or NPCS enter those overlap box
So I need to connect them in some way to make all this system work
make an event that when a certain player enters / exits an area it stores it in some type of collection, then when OnGameTimeChanged and you need to check if they are in that certain spot in collection, if they are not then you punish those not in that collection
what design patterns do you guys think are the most useful and least useful just in general
They're all useful for the most part..
some tops, observer, singleton , factory , command etc.
least .. don't overuse / abuse singletons
The most useful design patterns are the ones that fit the problems you need to solve.
Can anybody tell me why when i use netcode for gameobjects both of the players move with only 1 players input.
how to make some sort of paint decals?
like big droplet of paint leaving a splatter on wall
thanks
how to make a splatter of paint like a gel in portal 2
i think tht projectors will make fps go 0
Either using decals or a special shader that is able to show the "paint" detail based on some texture/vertex colours
decals?
howe to switch from urp
and i said\
no projector
because they are expensive
then you can research about the other thing I said
how to fix this
hi, im kinda new to unity hope u guys can tolerate e for asking a lot of questions
idk, noone knows
What is that? An area light?
no decal projector
i cant rn
and this is a code channel, if it's not code related...
does anyone know whats the meaning behind these codes
i can build apk for a while now, but suddenly it has an error when i tried building em
i think my last progress is when i tried to add firebase auth,firestore and database package to unity
can you show the full error message
sure
They're in packages.
If you're not using those packages, remove them. If you are, remove them then add them again.
-
Packages\com.unity.addressables@1d7f6a740e58\Runtime\ResourceManager\AsyncOperations\AsyncOperationBase.cs(39,32): error CS0433: The type 'Task<T>' exists in both 'Unity.Tasks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
-
Packages\com.unity.addressables@1d7f6a740e58\Runtime\ResourceManager\AsyncOperations\AsyncOperationBase.cs(39,32): error CS0433: The type 'Task<T>' exists in both 'Unity.Tasks, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
-
Library\PackageCache\com.unity.inputsystem@e2c83221d2dc\InputSystem\Actions\InputBindingComposite.cs(221,46): error CS0121: The call is ambiguous between the following methods or properties: 'System.MissingExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo)' and 'System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo)'
-
Library\PackageCache\com.unity.inputsystem@e2c83221d2dc\InputSystem\Controls\InputControlLayout.cs(1180,51): error CS0121: The call is ambiguous between the following methods or properties: 'System.MissingExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo, bool)' and 'System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo, bool)'
-
Library\PackageCache\com.unity.inputsystem@e2c83221d2dc\InputSystem\Actions\IInputInteraction.cs(326,56): error CS0121: The call is ambiguous between the following methods or properties: 'System.MissingExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo)' and 'System.Reflection.CustomAttributeExtensions.GetCustomAttribute<T>(System.Reflection.MemberInfo
there's a total of 15 errors but most of them are same errors
pretty sure not
use the search box then and find out
let me check it again to make sure
I think firebase used to include it in old versions
yea pretty sure not there
let me check firebase then
e.g.
delete and see if everything is fine. I dont even remember where they came from they just exist in our projects and get carried forward in the base ๐
Not sure which packages tho
I tried removing them multiple times but still there
you can search with explorer in Library\PackageCache
So after deleting, I should try build APK again right?
yea if thats what caused the errors to show last time
Yea pretty sure not removing unity.task
Ouh
Okay so it reduced the error to 8 now
Actually 6
Cause the other two are just compiler errors
I only left with inputbindingcomposite.cs and inputcontrollerlayout.cs
what is the best way to implement anti corner-snagging? I've tried using a (yellow) vertical raycast in front of the player (slightly behind the actual horizontal raycasts) and it works surprisingly well but I was wondering if this is a known method that has any downsides to it, or if theres a much better method
(also please ignore the blue raycasts, those arent the horiziontal collision raycasts)
Their names are literally in the errors
Yea I tried
Basically the best way to make any sort of character controller is to make them look like Pinhead with all the raycasts coming out of them at all times. In general, people don't do enough raycasts when making a character controller
you could also do a boxcast
I considered that and it did work well but it took around 40 raycasts to stop any noticeable snagging and jittering. Isnt that dar too many?
It's kinematic rigidbody so I need to know the direction to halt movement
*Kylo Ren meme*
MORE!
Actually? Idk if that's bad practice or not to just spam raycasts even if I can afford to do so
It's partially a joke, but also don't be afraid to just spam raycasts everywhere, they're incredibly cheap
Hello, I would like to know th best practice to manage multiple managers. For example, let's say I have Level Manager, Inventory Manager and Game Manager in my Level scene. When the player will go back to the Menu scene, all these Managers will be useless, and they could even break the game since some references (like player for example) won't be found. So, what is the best way to tell which managers I need and in which scenes ?
Best way is to ensure one-way data access to the managers, and the managers don't reference any specific objects in the scene that might not be there. That way, them being around in scenes they're not needed in is no big deal - things just won't actually be referencing them
can you not call a method from a generic interface from an action like this?
from any other source "damageable.TakeDamage()" works just fine, but calling it when this action is ran doesn't work
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
i was calling it with the wrong signature lol, my bad
just fyi its hard to see code as an image especially on mobile..
i want a working PC in my game, and idk what would be the best way to organize and instantiate new files. SO? Normal classes? Someone give me some orientation
depends on what you want to do
thats a very vague thing to suggest anything, we know nothing about your setup
i gotcha, i'll format it
I mean, I got this desktop where they are icons, which one with a specific file (just like a normal PC)
and u can also create new files, rename, etc
yes I understood the computer part, but what do you want to do with the files is more important to know
what do these files do?
depends of the type
SOs and POCOs are very similiar, so that goes also with the 
you have documents, audio, video, etc
I would probably use POCOs unless I have a specific reason to use SOs
what's POCO?
oh normal classes
the way id do it is have a generic "file" interface that supports being opened/closed or whatever you'd need, then have each unique file type implement it's own behavior, but that's having never really used SOs
hey guys i have a quick question for you i'm begginer with unity and i want know wath langage i need tu use
C#
btw all resources pinned in #๐ปโcode-beginner, or beginner questions
okay thx
Easily googleable
yeah but i want to be sure
So click on the links and confirm
thats from the official website
can't be any more legit / official than than a random on the internet ๐ I could've been lying
true
boxcast gives you that
Does it? I thought the data only told you if it collided with something and not the side it came from
Interesting.
you're probably confusing OverlapBox or CheckBox with BoxCast
Why do some people prefer doing simple raycasts over using a boxcast sometimes then if it does the job better (seemingly)
different tools for different purposes
if you want to cast a ray through the scene, use raycast
If you want to cast a box through the scene, use boxcast
Sorry I meant specifically for collisions
what about them
I've seen many people use simple line raycasts for kinematic collision detection so I'm unsure why they'd chose to do that over a boxocast
Probably because they don't know any better
Fair enough lol
I'd say most of the time it's a capsule shaped character and CapsuleCast.
I've done all of my collisions and movement features (auto stepping) with raycasts on a boxcollider ๐ญ
Works fine except when walking into vertices or walking along a vertex (the player bobs up and down because the corner can go between the vertical collision raycasts
This is a code channel, and that is not a code question. Delete and move to #๐ปโunity-talk
Does anyone know of any good up to date examples of server authoritative movement with client prediction and reconciliation
Hey,
are there advantages / drawbacks to use tag over component / script + TryGetComponent() and vice versa please ?
using tags you need magic strings
magic strings ?
if you're using this for static references, you should use serialized references instead
I'm not sure to understand what this means ๐ค
specific strings as identifiers, if you typo the string it breaks
if you want to just get the player or camera or whatever statically, you could set them in the inspector instead
but in the IDE if you use CompareTag, it suggests you all the existing tags so you don't have to type them by hand
that doesn't change the fact that they're magic strings though
if you rename a tag it also breaks
oh yeah, so it's better to use Components and TryGetComponent<>() ?
it suggests you all the existing tags so you don't have to type them by hand
pretty sure that's a rider-only thing and the vs and vs code definitely don't do that
Oh yeah I'm using Rider
lol yeah i could tell based on the fact that you have tags in your intellisense
it's better to used serialized references if possible
but tags aren't really comparable to getcomponent calls anyways, so not sure what you're really asking
if the options are compare tag vs trygetcomponent it sounds like this is likely for collisions rather than having direct references
tags give you gameobjects, getcomponent gives you components
Can't always do that. Here for instance I have an area that I need to check what entered it and if it's a Player or an NPC execute some code, so I could give both the same tag but it doesn't look like the best way as if I need those to have other tags I can't do that anymore, so that's why I thought about giving them a script component called "Entity" and check the thing entering the area if it has that script.
but TryGetComponent is typically going to be better if you're going to need to get the component. if you're not then a CompareTag is just fine and you can make it ever so slightly better by using a TagHandle rather than passing the string directly to the method
I'm asking because I'm facing that problem in my last messageโ๏ธ
Yes because I need to check an ID on the thing entering that trigger box, if it's a player or one of the NPCs, I need to save those in a list
then i guess you get the component and read the id from that
hey there, quick question:
I do have a script AbilitySystem that has a list of abilities ([SerializeField] private List<Ability> abilities;). my Ability is an abstract class (inheriting from ScriptableObject) that defines some basic things for abilities. I want to have abilities like Dash that simply inherit from Ability - but I'm unable to drag&drop the Dash ability into my ability list of my AbilitySystem. what am I missing here?
You should be able to do what you described, can you post some relevant code snippets and maybe a screenshot of the inspector?
probably trying to drag the script instead of an SO asset
can I use perlin noise and fft transforms in the burst job system or no?
I am trying to move my perlin noise generator to a burst compiler to increase performance but is this even possible?
It should
Hey, can anyone help with displaying an animation for a calculated random outcome? Doesnโt have to be an actual animation, could be animated with code.
For example a dice roll, it would be calculated but then needs to be animated to show the dice land on that number.
Or another example spin the wheel type thing, where the number chosen is calculated but it needs to land on the right number visually.
Km not sure where to start with this, and i cant find anything at all through googling, although im not sure exactly what to google for this.
This is quite difficult to implement and most games just fake it.
not sure how itโs faked
There could be many ways. For example, with the dices, there could be only one or several animations, and they know what side they would end up falling on, so they set the initial rotation or the assigned textures such that the desired outcome is displayed.
make up a random dice roll simulation so you know the outcome, put values on the sides that you want, run it again with the numbers
im still not exactly sure how this helps and i feel its missing a ton of context. Can you explain in what way this dice roll effect would be shown to the player? And i think this quickly gets more complicated if there are multiple dice.
if the random outcome is calculated, generally displaying said outcome is "calculated". a majority of games do not pre-calculate random outcomes then dynamically handle displaying them (in this case the physics of a dice rolling)
Let's say an animation always ends up showning side A on top in the end. Then before starting the animation, they calculate the random result(1-6 for example), and set side A to have that result. Then run the animation
No. You only need 1 animation
no you'd have 6 animations that can be played on 1 dice 4 times
You seem to be missing the point
Oh okay, this actually just gave me the point!!
I see what youโre saying now
One animation, and just place the faces on the sides so that the one you want ends up on top
Is that what youโre saying?
Yes
is there any way in unity to make [CallerFilePath] use relative paths instead of absolute? I know how to do that in .NET but I have no idea how to do that in unity
I found a way by adding -pathmap:PATH=. but now I have the problem that I have to hardcode PATH, I don't know how to use environment/project variables in csc.rsp file
I tried -pathmap:$(MSBuildThisFileDirectory)=. and -pathmap:$(SolutionDir)=. but neither work
is it possible to add C# compiler options in editor scripts before build?
hi
Can someone tell me why despite having using Unity.Services.Multiplayer; in my code
Lobby can't be resolved?
Assets\Scripts\MainMenuHandler.cs(10,13): error CS0246: The type or namespace name 'Lobby' could not be found (are you missing a using directive or an assembly reference?)
thanks in advance
because using only dumps names in the namespace into file global scope so you don't have to type fully qualified name but it does not actually add any references to project/assembly/package
make sure that package containing that class is actually added to project
yeah
I think I did
I mean I installed it from the Package Manager
look if you need to maybe add assembly reference manually with -r:assemblyname parameter csc.rsp file or into asmdef file if your code is in the library
i don't even know what this assembly stuff is ๐ญ
what version of unity are you on
Does that package even include a type called Lobby?
From what I know it should
Hint: look in the documentation
you don't but packages usually have, but unity ones should all be set to "auto referenced" so you don't have to do anything else usually and yes, you're right, based on documentation it should have Lobby class but it's in the Unity.Services.Lobbies.Models
it says "Lobby" is in the Multiplayer Services SDK
doc is pretty garbage like all unity docs
Is your IDE configured so you see red underlines for errors in your code?
so try using Unity.Services.Lobbies.Models.Lobby instead
thank you very much, I'll try that
Instead, since the namespaces have been changed in the latest version, they should use the quick actions in their IDE to add the correct namespace
I got the C# and Unity Extensions for VSCode, nothing is turning red when somethings wrong
make sure unity also has VSCode extension, VSCode is selected as editor and you use "regenerate .csproj"
that might help
well now im getting totally different errors
but that should be due to the Lobby finally getting recognized
thank you very much guys! ๐
if you correctly configure VSCode you can fix that with Ctrl+. on these classes
also if you want to use C# 10 in unity you can also do that
for future reference for everyone here:
(from #854851968446365696 )
is it possible to use environment variables in csc.rsp file?
Hi there, i was experimenting with using input system to make a local multiplayer game, but using the player input component and player input manager, i can only join with the keyboard, and my controller (Xbox series controller) does not work. I checked in the input debugger, and the controller is being detected, so i'm kinda at a loss
Here are the related screenshots
likely control scheme related
Why use IL2CPP vs. Mono? I see that generally IL2CPP offers better performance. I imagine that is still true since it's AOT compilation. However, I also see IL2CPP can introduce a lot of weird errors
- Better Performance
- It's available on more target platforms than Mono
Thanks. I have used IL2CPP in the past because my previous projects required it for the platform we were targeting. Working on a different project for PC now so contemplating Mono vs. IL2CPP. I remember we had a lot of weird issues with IL2CPP
I find that IL2CPP issues are quire rare and usually isolated to reflection-based stuff.
Good to know. My prior projects were for Universal Windows Platform... which doesn't really get much support. So I imagine that was a part of our problem
probably yes
somehow this script makes my fps go from over 280 to barely 90
Use the profiler because it's not likely to do that unless you have a billion of them running (over exaggeration, but you get the point)
the lag was due to the Vector3 being a public and showing in the editor
probably some wierd issue with the unity editor playmode
Serialization causing lag is weird
is there a #support here? Because i need some help
With?
they're all help channels #๐โfind-a-channel
why are you using unity 2017 lol
Should ask in #๐ปโunity-talk as I don't think that there's a channel for that
Definitely not code related
Making a Wii U game, and it needs that specific reason
Ok, will ask in there
old U version, unsupported target platform, issues getting stuff to run --> red flags, likely some things invovled that we don't talk about here
Remember that person who was using unity 5
Best to keep up with the oldest version with support which is 2022 rn (2021 I think has extended pro support)
Can someone tell me what it means if you get this error, despite having set all dependencies (dragging the Button Component into the Button Field of the Canvas > MainMenuHandler Script in this case) ?
Initialization error: Object reference not set to an instance of an object
UnityEngine.Debug:LogError (object)
MainMenuHandler/<Start>d__7:MoveNext () (at Assets/Scripts/MainMenuHandler.cs:84)
System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start<MainMenuHandler/<Start>d__7> (MainMenuHandler/<Start>d__7&)
MainMenuHandler:Start ()
well, check what's on MainMenuHandler line 84
perhaps something was unassigned at runtime
Debug.LogError("Initialization error: " + e.Message);
or maybe you're looking at the wrong component
oh you're logging that manually, rather than having it throw itself?
I just catch an exception there and log that
here's what I do that throws the error:
playButton.interactable = true;
I just access the button and set interactable to true
add gameObject to the log as the second argument, so you can see which object it's logging from
it might not be the one you're looking at in the inspector
ohh okay
I have some weird problem where I use
Destroy(gameObject, 5f);
```Now if the 5s aren't up when I exit the play mode, the object is apparently saved in the scene. Is there a reason for that? context might be important, it's instantiated as child of a dontDestroyOnLoad object
Initialization error: Object reference not set to an instance of an object
UnityEngine.Debug:LogError (object,UnityEngine.Object)
MainMenuHandler/<Start>d__7:MoveNext () (at Assets/Scripts/MainMenuHandler.cs:84)
System.Runtime.CompilerServices.AsyncVoidMethodBuilder:Start<MainMenuHandler/<Start>d__7> (MainMenuHandler/<Start>d__7&)
MainMenuHandler:Start ()
Now it logs this
the exact same as before???
click (or double click? i forget) the error to highlight what object it's from
In a game where the UI is part of the gameplay (like pokemon, FF, etc).
What type of class is responsible for controlling the UI?
Like would the battle system be calling the UIManager?
Or the turn system calling the UI?
Or others?
are you sure it's this line
CombatManager with CombatUIManager
Usually the idea is the UI invokes events it has subscribed on the CombatManager, but if you don't care too much for that I'd just reference it directly.
no
XD
try
{
await AuthManager.Instance.InitializeAsync();
isInitialized = true;
// Slight delay to ensure UI updates
await Task.Delay(100);
playButton.interactable = true; // Enable the Play button after initialization
if (statusText != null) statusText.text = "Ready! Click Play to join.";
}
catch (System.Exception e)
{
if (statusText != null) statusText.text = "Initialization failed: " + e.Message;
Debug.LogError("Initialization error: " + e.Message, gameObject);
}
that's the entire try catch block
try narrowing it down then
or could just comment out the try/catch bits so it points to where the error actually comes from
yeah so i let it log itself
just throw the exception
I'll try that
ohhhh
now it makes more sense
NullReferenceException: Object reference not set to an instance of an object
MainMenuHandler.Start () (at Assets/Scripts/MainMenuHandler.cs:72)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) (at <314938d17f3848e8ac683e11b27f62ee>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
UnityEngine.UnitySynchronizationContext.Exec () (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
UnityEngine.UnitySynchronizationContext.ExecuteTasks () (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
Line 72: await AuthManager.Instance.InitializeAsync();
So if I understand correctly, supposing I'd want to show different stuff.
Like turn number or damage dealt or possible moves or confirmation for a move (like "are you sure you want to evolve this unit?")
The CombatManager is responsible for listening to all these events and preparing the relevant data for the CombatUIManager, right?
yeah that was the other thing it couldve been, i was suspecting that lol
The CombatManager does not need to know about a UI at all basically, and usually for decoupling reasons you'd have some event system where the UI would subscribe to so it bridges it between it and the CombatManager, but we're talking about the most proper case here but in reality I've dont have time for that.
So, if you do want callbacks from the CombatManager, a bi-directional reference can suffice
Yeah I meant as events.
I just mean like: instead of each action doing an event that the UIManager listens to (which may cause different events to interfere or make it hard to track down references),
Would the combatManager act as a proxy that processes the events then raises the appropriate UI events? Or did I misunderstand?
UIManager -> Invokes event for what the user has selected -> delegates to a method inside of CombatManager (for example the player pressed Attack)
UIManager however may also need callbacks for say stuff like updating statistics like health and game state related information, so it'll also have to subscribe to those methods on the CombatManager.
This would require some reference to bind those events, but otherwise you can also make a event bus that acts as the inbetween (proxy)
put each ability in its own file and add the AssetMenuAttribute there, otherwise how does it know which one to create? then you need to actually create an instance of that
everything is in one file, it was just easier to create the gist this way ๐
if creating an instance of these abilities is the only way to achieve that; is there an alterantive? having multiple Dashes seems counter productive
okay, let's ask differently: would this approach be any kind of bad practice?
not necessarily, plenty of folks go that route
like anything, it depends on what you're trying to accomplish
since a lot of ppl talk about scriptable objects as data containers it seems a bit weird since I'd like to implement the logic of how an ability works also in that class
would that be possible or even wrong?
simply put: an ability system that can dynamically add/remove abilities, where abilities (like dash, shoot, etc.) implement the logic of how they work
it can work, you just end up having to pass a lot of things into those method calls or some kind of larger context
sure but that's just 'I want to be able to implement anything in my video game completely abstractly' which is not really anything
true ๐คทโโ๏ธ ๐
this architecture is essentially commands/actions with some weird indirection in exchange for being easily editor configurable
whether that tradeoff is worth it will be up to you
ok thanks
Instead, you should use ScriptableObject as "Factory". By example,
public abstract class AbilityDefinition : ScriptableObject {
public abstract Ability Instantiate();
}
public class FireballAbilityDefinition : AbilityDefinition {
public override Ability Instantiate()
{
return new FireballAbility();
};
}
I'm getting hundreds of these messages about the font and they're flooding my logs making them unreadable
I have "Include Font Data" toggled, I do not understand
this is a code channel, try #๐ผ๏ธโ2d-tools, #๐ฒโui-ux, or #๐ปโunity-talk
You can add [TAG] into your owns log if you are simply attempting to see your own log and are not interested in fixing the issues. Also, you can use the Collapse option such that error that repeats are all under the same log.
Collapse helps in the editor but not in the player.log
If you are inspecting the log manually, you can use a tool to do a search and replace.
Notepad++ and regex can probably works.
I really don't want to be replacing 900k of lines every time I run the test runner
actually 16k, but point stands, I want to fix this, not ignore it
In basic terms,
oops wait
In basic terms,
If I have a rigidbody2D, and on the Update() function i have an 'if (Input.GetKeyDown(x))' {PerformJump()},
is there a way to call the function only on the next FixedUpdate() frame? is it worth the effort?
is there a way to call the function only on the next FixedUpdate() frame?
yes
is it worth the effort?
depends on how you're jumping, i guess?
if you're just doing an impulse-type addforce, then, no, you can do that whenever. it doesn't need to be in fixedupdate
Just realized I didn't explain what the function does, but yeah, it adds an impulse of force.
i mean, "performjump" is pretty self-explanatory
but if there's more stuff that does rely on being on fixedupdate, then it's not too hard to do
just queue it up and consume that in the fixedupdate
So if I wanted to do a timed-jump mechanic, like with short jumps and high jumps based on the time holding the key, should that be done in fixed update?
could be a bool if it should only be called once, could be an int if it could be called multiple times (if the key was pressed multiple times in that 0.02s gap), could be a list/queue of actions to handle multiple functions with the same behavior
should what be done in fixed update?
Nvm I can work through it myself lol
Making it too complicated in my head
there's a lot of ways to do that system, it might be split up over update/fixedupdate
yeah, for my needs I've mostly been sticking to fixed update, Its just GetKeyDown thats been giving me trouble
doesn't seem unreasonable for unity to be able to queue something like that internally, but I'm using a dated version anyway lmao
input is frame-bound, they update on frames only
GetKeyDown is true for the 1 frame it was pressed on
if FixedUpdate happens to miss that frame, too bad
it's just not logically correct
HI! I am trying to import a shared library I have written into unity, but I am having some trouble. On import, I get the following error:
"TypeCache is unable to load info on field .FindServerForPlayerResponse::<FoundServer>k__BackingField. Are you missing a reference?"
Basically saying that its having trouble with a backing field for one of the values. However, the way that I have the shared lib written shouldnt really have any issues, the field it refers to is just a bool, and when I try to remove it, it just says that the issue was found with the next variable I had defined there, so I am just assuming its an overall issue with the DLL, which googling seems to conform
The library is only a few files that have response/request packet data, an example is as follows:
using Network.Attributes;
using Network.Packets;
[PacketRequest(typeof(FindServerForPlayerRequest))]
public class FindServerForPlayerResponse : ResponsePacket
{
public FindServerForPlayerResponse(bool foundServer, int serverId, string name, string publicIpAddress, int port, FindServerForPlayerRequest request) : base(request)
{
FoundServer = foundServer;
ServerId = serverId;
Name = name;
PublicIpAddress = publicIpAddress;
Port = port;
}
public bool FoundServer { get; set; } = false;
public int ServerId { get; set; } = 0;
public string Name { get; set; } = "";
public string PublicIpAddress { get; set; } = "";
public int Port { get; set; } = 0;
}
Ive tried changing the framework it targets, ive tried changing unity to target the .net framwork or .net core in the player settings but nothing clicks
If anyone has dealt with a similar issue, please let me know if you know how to solve this sort of thing
Is anything referencing this class? Maybe it's getting stripped or something
Yes I have a few other projectrs that reference the project in my solution and use the class
It compiles and works just fine in the normal vs/C# context but just has trouble when brought into unity
Update: Found it! I needed to manually type that the target was dotnet standard 2.1 in the actual csproj file and unity finally accepted it
Thanks for help regardless :D
I know this isnt really a unity (or even coding) question, but is there a way to turn off these spaces in visual studio?
Yes, you will probably find something on google pretty quickly.
Searched there first, didn't find anything relevant. What should I search for exactly?
https://www.reddit.com/r/VisualStudio/comments/1bsbq2r/can_i_somehow_stop_these_reference_lines_from/?rdt=34466
https://www.reddit.com/r/vscode/comments/8cpvs1/remove_0_references_text_in_c_file/
https://stackoverflow.com/questions/65567250/how-to-get-rid-of-references-code-annotation-in-vs-code-c-dotnet-5-project
inlay hints, codelens, that kinda stuff
only needed one, but thanks lmao
me, or the other guy?
the other guy, absolute wall of embeds lol
found some really confusing and inconsistent code, i set a class in my mono behaviour that's supposed to be null at the start of the game(which i supposedly achieve by putting class = null at the start function). But for some reason it doesnt work sometimes
if the field has no value by default and is not serializable, it will remain null. Share the code
isnt there a format for sharing code? i forgot how to do that
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
๐ 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.
A class can't be null. A variable that holds an instance of a class can be null. A reference variable is null until you set it.
i presume they meant a field but tru
sorry, i did mean an instance of a class. It keeps reapearring as new instance instead of staying null until my code replaces it
also would putting [NonSerialized] help my case?
yes but share the code...
A variable doesn't just stop being null without your code setting it to something
yep that's what ive been trying to figure out, but for now atleast i managed to solve the problem by just putting the nonserialized attribute before the class instance
what was the field type then?
yea that doesn't stop serialization
and with the HII attribute it just gives it a default value anyways :p
while nonserialized automatically sets it as a null from the beginning
yea any serialized field gets given a value (e.g a List will not be null as unity will give it a value)
what im confused about now is how it didnt turn null when i literally wrote "classInstance = null" at the start function
what i dont understand is WHAT IS THE TYPE
class type? a custom one
and the class type is serializable so that i could other instances of it on the inspector
thx ๐ญ
I presume the inspector overrode the value to not be null due to it being SerializeField
in a build it should act differently
Otherwise use a custom inspector to draw this information
ye i think that by putting serializable on the class itself, all instances are all bound the not be null
no its due to this quirk with unity serialization and only this situation shows this behaviour
anywhere else the class acts like we expect
dang, I gotta read that documentation on how serialization works and shit
the serialize ref doc page explains how it allows storing sub types and null
ty for that again
from the page:
// This field must use serialize reference so that serialization can store
// a reference to another Node object, or null. By-value
// can never properly represent this sort of self-referencing structure.
[SerializeReference]
public Node m_Next = null;
I'm making a rotating tiles puzzle, as in, there's a grid of stationary square tiles (GameObjects, not Tilemap tiles) depicting various pipe segments, and you have to click and rotate all of them to make the pipes connect from one side to the other.
The visual part was easy, but now I'm wondering if my idea for checking the connections is too complicated because I'm missing some convenient Unity feature.
My thought is for each Tile to have a list of Directions (as an Enum) its pipes are pointing, and references to its neighbours, so whenever it rotates, it can poll its neighbours which Directions they're pointing, and there's a left/right or up/down match between them, save that Direction(s) in a 'connection' list, then tell all its neighbours to update.
And when checking the connection (at the end, not dynamically on every update), I'd start from the entrance tile and recursively find its furthest connection by asking all neighbours for their furthest connection, until I get back a bunch of Null for dead ends, or the exit tile.
I'm aware this description is kinda rough and inaccurate, but it's not about the implementation yet, but the general idea. Am I missing some Unity/C# feature that would make a lot of that work redundant, or am I generally on the right track?
Guys, is there anything better than a character controller if I don't want all the forces from a rigidbody?
I don't trust my own hardcoded collision. Is there really not anything else?
If you have a grid of tiles and know their directions you can walk from the start to end to check if the path is complete. There are many famous algorithms that can do pathfinding such as A* or Dijkstra's algorithm
wdym "all the forces"?
you can disable gravity and linear damping if you want
I meant if I used a rigidbody instead
yeah what do you mean by "all the forces"
you can disable the built-in forces and you could just not AddForce if you don't want to
what's the issue with a rigidbody
it just jumps around and jitters
it fucks around a lot
which a char controller doesn't do
but char controller has some limitations that make it unviable to me
and with a kinematic rb without gravity, I thought moverotation would check collisions while rotating but it doesn't
are you controlling the transform
or what
then you're using it wrong yeah
oh no sorry
rigidbody controls transform
