#archived-code-general
1 messages ยท Page 138 of 1
You could also use regex if you were so inclined
is there any possibility to remove TMP_Text's line itself?
maxVisibleLines
it may change the string
it's not that, I still need it to wrap
When I say "it" I mean what Nom mentioned
if you want to actually change the text, you have to actually change the text
oke, fair enough
thanks
if (_textComponent.textInfo.lineCount > _textComponentLineCount)
{
string lastWord = _textComponent.textInfo.wordInfo[^1].GetWord();
//text = text.Substring(0, text.Length - lastWord.Length - 1);
textComponentIndex += 1;
text = lastWord;
print("new textComponent added");
}
what's wrong here?
NullReferenceException: Object reference not set to an instance of an object
TMPro.TMP_WordInfo.GetWord () (at Assets/#Scripts/Builtin/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMPro_MeshUtilities.cs:195)
TMPro.TypingField.Update () (at Assets/#Scripts/Helpers/TypingField.cs:156)
which line is 156
string lastWord = _textComponent.textInfo.wordInfo[^1].GetWord();
_textComponent is prolly null
you'll have to break that line down and figure out which piece is returning null
Probably wordInfo or wordInfo[^1] is null
but I would guess textInfo isn't guaranteed to have a wordInfo or something
no
I have debugged it and in wordInfo array's last 6 components's textComponent is null
that's strange
indeed
wordInfo[^1] does not have textComponent
it sounds like I need to find it manually
this kinda sounds like a bug tbh
that's unity's issues probably
I think I should
string lastWord = text.Split(' ')[^1];
that's going to be way less efficient than the LastIndex and substring approach I mentioned earlier
since it's going to allocate a ton of strings and an array
only for you discard almost all of it
do I get last index of ' ' ?
whatever you want to split on,yeah
more like
It's not a bug. There is wordCount assocated to the array, since the array isn't always filled (it's increased based on allocation requirements).
_text.ForceMeshUpdate(true);
var textInfo = _text.textInfo;
Debug.Log($"{textInfo.wordInfo.Length} vs {textInfo.wordCount}"); // 32 vs 18
var lastWordA = textInfo.wordInfo[textInfo.wordCount - 1];
var lastWordB = textInfo.wordInfo[^1];
Debug.Log(lastWordA.GetWord()); // fdsajfdsfdsfsdasfd
Debug.Log(lastWordB.GetWord()); // inner usage gets null data, so exception
More like:
int lastWhitespace = text.LastIndexOf(' ');
string lastWord = lastWhiteSpace == -1 ? text : text.Substring(lastWhitespace);
unless this works to get a substring text[(text.LastIndexOf(' '))..]; but that looks like Python not C# to me ๐ฎ
that does find
works almost like substring
but range
string[(from index)..(to index)]
and yeah, there is a possibility that there is no space
that's strange
it works with arrays too
int[] bla = foo[2..];
I mean it's a feature of the indexer operator itself it seems []
yeah, it is
neat discovery ๐
I wonder why you don't know it too ๐ค
yeah, that's it
I'm still very new to C# ๐
you have helped me a lot before though.
Slicing creates a new array ๐. Can use a span to have a range inside the existing array instead.
int[] slice = arr[2..]; // new array
Span<int> span = arr.AsSpan(2..); // slice over existing array
that's something new already.
you can also resize array btw
public static void Resize<T>(ref T[] array, int newSize);
Which is kind of a naming lie, since it doesn't "resize" the actual array. It makes a new one of the length and does a buffer copy to the new one.
well thats what resizing an array is regularly
yes, it changes real array's size
I don't understand.. I touch the gem, and nothing happens
public class PlayerController : MonoBehaviour
{
public float speed = 5f;
private Rigidbody playerRb;
private GameObject focalPoint;
public bool hasPowerUp = false;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
focalPoint = GameObject.Find("Focal Point");
}
// Update is called once per frame
void Update()
{
float forwardInput = Input.GetAxis("Vertical");
playerRb.AddForce(focalPoint.transform.forward * forwardInput * speed);
}
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Powerup"))
{
hasPowerUp = true;
Destroy(other.gameObject);
}
}
}
is the text stored differently, how come u arent splitting by \n
cause u said last line, but this is last word
Your powerup's collider does not have isTrigger set, but your code only handles collisions with trigger colliders
Oh.. weird.. I guess I missed it in the tutorial?
I think so, yes - I don't remember such a caveat in that unit ๐
Yeah, you'd just be surprised at the amount of people that think that arrays can actually change their own immutable length. Reminds me of people who don't realize that Lists are just arrays that copy into larger new arrays when needed, and instead think they are magically different. 
I tutor, so i am unfortunately well aware at the misconceptions people have. Tbh given that a lot of beginners* here seem to learn c# and unity at the same time, i doubt many are familiar with anything relating to data structures or algorithm problem solving
Sounds about right yeah
hey, from my POV, it's magic โจ
Yeah, that's true, but I actually need last word. I need to get lastWord when 4th line is added. This line is added just when new word is typed
no, wait, actually
if there are no spaces
yeah.
that's true, I need \n
thanks
I realised it while typing
Tutorial(image)
My image(with the bug)..
Why?
ienumator is not ienumerable
I had this issue this typo some time ago too
no, actually
TMP_Text does not have \n
it's not splited by new line
word's position is changed
static async Task unloadAsync(string SceneName)
{
AsyncOperation operation = SceneManager.UnloadSceneAsync(SceneName);
while(!operation.isDone)
{
UnityEngine.Debug.Log("unloading: " + operation.progress );
await Task.Delay(1); // Which is better? Task.Yield(); or Task.Delay(1); ?
}
}
static async Task enablePreloadedScenes(SceneCollection targetScenes)
{
// ... some stuff such as setting adding scenes to List<string> UnloadScenes
await scenesAreActive();
Task[] unloads = new Task[UnloadScenes.Count];
for (int i = 0; i < UnloadScenes.Count; i++)
{
unloads[i] = unloadAsync(UnloadScenes[i]);
Debug.Log("unloading: " + UnloadScenes[i] + ": " + unloads[i].Status);
}
UnityEngine.Debug.LogError("never passes this await"); // none of the unload tasks ever gets completed as their progress is stuck at 0.0f
await Task.WhenAll(unloads);
// ... Rest of this async method
}
im having an issue where the AsyncOperation in the unloadAsync method never goes past 0 progress. im not entirely sure why this happens. can anyone give me some pointers?
the reason im doing it this way was i thought that i could let all the scenes load at the same time instead after each other like most tutorials do. Maybe there is a reason they do it that way?
\n is just an escape sequence, so you can definitely use it inside tmp. But i understand what u mean, I thought u added the newlines
my mistake
no, TMP_Text wrappes words itself
no, I haven't explained it correctly
@lean sail I think I have found the solution, just in case you are interested
string lastLine = text[_textComponent.textInfo.lineInfo[^1].firstCharacterIndex..];
oh, no, wait
forget it
that's so dump
no, wait
actually
it shouldn't return 0, right?
so yeah
it's correct
i think i found the issue, im allowing it to load in new scenes too quickly so it should wait before its allowed to
yep, that fixed it
Thanks ๐
๐ฅฒ
Hello. I'm trying to figure out how to determine if an attribute is defined on a behavior or not (class or otherwise) to figure out if it's got a PunRPC on it or not.
Digging through MS's docs & stackoverflow suggests it should just be as simple as ArbitraryMonobehaviorType.IsDefined(typeof(PunRPC)), but that clearly doesn't work, otherwise I wouldn't be asking. In my case it always returns false, even when ArbitraryMonobehaviorType is a type that 100% has a PunRPC on one of it's methods.
Do I need to iterate through every method in the type and check that?
PunRPC is an attribute that goes on a method so yes you'd have to check the methods
Gotcha. Figured as much but just wanted to make sure I wasn't doing something peabrained w/ isDefined ๐
I'm multiplying a normalized vector by the deltaTime, in editor it usually goes to 0.00XX decimal cases but in build it seems to get bigger, going to 0.0XX, which makes a later multiplication much bigger than it's supposed to be. Does anyone know why this happens?
deltaTime changes based on framerate
That's the whole point of it
If that is breaking your code you have used it incorrectly
Yes, I know, but both the editor and build are running at a locked 60 frames per second
Apparently not - at 60 FPS deltaTime will be roughly 0.0166... If it's 0.00XX in the editor, then the editor's framerate is in excess of 60 FPS
Application.targetFrameRate is set to 60
this also sounds like a problem, yes
If they were truly the same framerate you would have the same deltaTime
And regardless:
#archived-code-general message
Maybe show the code
And we can suggest a fix
It is running at 60, I can see it in the stats
Stats window is false
Use the profiler and/or an actual framerate calculation from code
really? didn't know it was erroneous
Damn, that's not good
I'll see if I can source the info from somewhere else then
It's well known to not be accurate
in all the examples i have come across about UnityAction's they all just simply say doing this should work
UnityAction myAction;
myAction += someMethod;
// ... Later
myAction();
// or
myEvent.addListener(myAction);
but when i do this its telling me myAction is not set, which makes sense but i cant seem to get any valid constructor. what am i doing wrong?
can i actually cap fps in the editor?
where does this error occur
I think you're focusing on the wrong thing though. You will never get a guaranteed constant framerate. You need to fix your code to work at different framerates
at myAction += someMethod;
Yeah, this code is a few months old, I'm trying to fix it, but, looking at it now, it may not need the delta time calculation at all, I'll check and will return if needed, thanks
I'm getting a weird wobbling on my on screen joystick when i hold it close to the center. Any idea what might be causing it? https://hatebin.com/tngakntihq
seems like i just cant have the action declared within a method 
ah, because it needs to be initialized
when it's a serialized field, it'll get initialized by unity for you
i dunno about using it as a local variable. not sure why you'd want to do that :p
the main draw is having that nice inspector UI
im just experimenting with async methods, wanted to test if i could use an action instead of a completion event
as that would be easier to pass in through a method
but maybe there is a better way
i guess Task.continueWith() is similar functionality of what i was looking for by doing that
So I have this problem where I have this client gameObject, but when using unitys netcode, for some reason the clients physics completely break when I try to use rb.Addforceatposition, addforce seams to work, but when I do atposition my client gameObject just glitches and flies all over the place. This doesn't happen to the one hosting the server
might be running on both client and server at the same time?
that's the issue i usually see, accidentally running code on both sides that applies to 1 object
I don't think so, I mean shouldn't client network transform handle sinking over the network? I mean the rest of my code is literally the same as if it wasn't a multiplayer game, but with the difference that I check if this is the owner, so that you don't control both players at the same time.
you're using Client Network Transform on it
that means that the client owns the transform
however, I'm not sure that Network Rigidbody expects that
use a Network Transform
I will try, do you by any chance know why I can't acces, ReuquireOwnerShip thingy?
with rpc's I should be able to this, says the docs, but RequireOwnerShip just doesn't seam to exist cs [ServerRpc(RequireOwnerShip = false)] void PhysicsServerRpc()
no not typo, intellisence doesn't show it to me and also I get error without typo
nevermind I don't get an error intellisence was just a big dumbfuck and didn't let me autocomplete
why is in this case is owner not working? the host can just move both players but the client can't move any cs private void FixedUpdate() { if (!IsOwner) return; PhysicsServerRpc(); } [ServerRpc(RequireOwnership = false)] void PhysicsServerRpc(){ //Moving player with addforceatpos.. . . . }
#archived-networking
also add debug logs to see why. Its likely just your host reading input then and not the client
Hi, I made a 3D printer in a game and now I want to be able to actual "print" gameobjects. To do that i need to be able to cut gameobjects at a specific height to slowly display more of the gameobject. Any Ideas how I could do that?
oh didn't know there was a channel for that sry
do you need the actual mesh collider to be built during runtime? Or is it just a visual effect
visual
I mean for input I just did this cs void Update() { if (!IsOwner) return; InitializeServerRpc(); } [ServerRpc(RequireOwnership = false)] void InitializeServerRpc() { input.x = Input.GetAxis("Horizontal"); input.y = Input.GetAxis("Vertical"); }
I would just spawn the object in, and use a shader or something to slowly reveal it
I don't know much about shaders, can I somehow control at which speed and when the shader reveals it using code?
you should add debugs to see where this code is running
server rpc means the code runs on the server. Your player is not providing its own input
hm, so it shouldn't be an rcp right?
Yes your shader can take values which u can change during runtime. It'd just appear on the material like the image shows. although I know so little about writing shaders, i only use shadergraph with tutorials. You should checkout the #archived-shaders channel for the smart people in this topic
thank you, you already helped me a lot <3
i personally wouldnt run an rpc every frame. I dont really know the best practice, I made my input use network variables that only the owner can set. Then the host moves everyone based on these variables
I can't really seem to get the timing right on this coroutine. it seems to always run within a second, even with parameters different...
The animationTime variable is set to 3, which would lead me to assume 3 seconds pass before this animation finishes, but its taking one second and just waiting the remaining 2
IEnumerator MoveInternal(GameObject moveTarget)
{
float currentAnimationTime = 0;
_isAnimating = true;
while (currentAnimationTime < animationTime)
{
var calculatedPosition = moveTarget.transform.position + new Vector3(0, GetComponent<MeshRenderer>().bounds.size.y / 2, 0);
transform.position = Vector3.Slerp(transform.position, calculatedPosition, moveCurve.Evaluate(currentAnimationTime / animationTime));
currentAnimationTime += Time.deltaTime;
yield return null;
}
_isAnimating = false;
}
for context, im trying to move a gameobjcet based on the properties of a curve over a timer
you should add debugs to see what these variables are set to. Because we dont really know what moveTarget is, or what curve you are using
also u might wanna at least cache some of those variables, GetComponent<MeshRenderer>().bounds.size.y i doubt this needs to run every frame
yea, fair point. still testing this out and noticed the object was moving too far down so I fixed that. good point tho, I fixed it right away
moveTarget is a different object in the scene taht I clicked, so the position is being lerped between the current position and the target position
you may want to store the initial position, because right now u are running Slerp on a vector that is constantly changing. So the distance from a-b is becoming less and less while t increases
the value of moveCurve.Evaluate appears to go from 0 to 1 over 3 seconds, which is expected
oh crap
I forgot about that
that fixes the timer of the movement, now I just need to change it so it uses the Y value of the curve to make the character kinda jump up
I may not be able to use standard lerp for that and have to do it custom I tihnk tho?
So I have debuged a little more and it tunrs out that input isn't the problem the server just doesn't move the clients gameObject no matter what
i dont think your curve specifically should be used for the vector. I guess u could use it, but u are also using it for your lerp, so you'll have a difficult time using it for both
I tihnk I figured out how it should function```cs
IEnumerator MoveInternal(GameObject moveTarget)
{
var calculatedPosition = moveTarget.transform.position + new Vector3(0, GetComponent<MeshRenderer>().bounds.size.y / 2, 0);
float currentAnimationTime = 0;
_isAnimating = true;
var origPosition = transform.position;
while (currentAnimationTime < animationTime)
{
var evalValue = moveCurve.Evaluate(currentAnimationTime / animationTime);
transform.position = new Vector3(Mathf.Lerp(origPosition.x, calculatedPosition.x, currentAnimationTime / animationTime),
origPosition.y + evalValue,
Mathf.Lerp(origPosition.z, calculatedPosition.z, currentAnimationTime / animationTime));
currentAnimationTime += Time.deltaTime;
yield return null;
}
_isAnimating = false;
}
you should probably split that up, for readability sake
but i guess if your curve determines the height the player jumps, then it should be fine
you can also cache the currentAnimationTime / animationTime so you arent calculating it 3 times
ya, now that it works. next step is to do some cleanup
I wanted to get that stuff working before I messed around with sorting it all out
ok so i tried the awake function but it still calls the awake in the script attached to the Main Camera first and then the Game Manager where I state the singleton Pattern
YOu shoul;d have put the stuff int he camera script in Start
note what I wrote about doing stuff that depends on other scripts in Start
ohh yes my bad as start is called anyways after update
if i first hold SHIFT (FineTurn bound key) then press A or D (Turn bound axis) it turns slowly alright
however if i first press A or D and then press SHIFT while holding A or D, it will continue to turn fast, disregarding FineTurn.
how can i fix that?
apply the fine turn effect when rotating
you're doing it in Turn, which sets turnInput
so pressing or releasing shift while you're turning will do nothing
because turnInput can only change when you press or release the A/D keys
rewrote it like this
public void Turn(InputAction.CallbackContext context)
{
turnInput = context.ReadValue<float>();
}
public override void Move()
{
fineTurn = playerInput.actions["FineTurn"].IsPressed();
rigidbody.angularVelocity = turnSpeed * turnInput;
if (fineTurn) rigidbody.angularVelocity *= fineTurnFactor;
rigidbody.velocity = transform.up * moveSpeed;
}
public override void Start()
{
base.Start();
playerInput.actions["Turn"].performed += Turn;
playerInput.actions["Turn"].canceled += Turn;
}
would there be a classier way of doing that?
sounds reasonable to me
is there a way i can build a cubemap from scenes at build time? i'd like to be able to have scenes specifically for creating some static skyboxes that are rendered from a camera placed inside them at compile time, that way i can reuse those textures as skybox cubemaps in actual levels.
i have no idea if something like this is possible. my current idea is to have a baking process you can initiate from within the game that cycles through each skybox scene, renders to a cubemap, and then saves the cubemap in some sort of persistent storage. i believe source does this for reflections, but per-level.
completely possible
and rather simple, but tedious
you will have to sit there hardcoding in camera rotations for each side
since cubemap has specific rules for each face
right, i see. i assume i could just save the render textures to the resource hierarchy?
or update existing ones, rather. that way it's easier to just set my skybox material to a known resource.
you stamp them into a large one, large one you write with EncodeToPNG , dont remember exact name
right i see. makes sense
goes on disk, imports as normal image
yeah that's what i was thinking i'd have to do
is there any way to automate this at build-time? or would i just have to, for example, have some debug state that lets me build skybox cubemaps?
yes there is
youd have to hook some editor static to build callbacks https://docs.unity3d.com/ScriptReference/Build.IPreprocessBuildWithReport.OnPreprocessBuild.html
ah i see! thank you ๐
that should be just a point you call your cubemap build
you probably need editor tooling for it to also update at edit time
you dont need a special state to do things like this, you can store the scene you are in, load cubemap scenes and build them with automation, and return to the scene you were in when its done, with EditorSceneManager
all that with a button press, is what i mean
Is there a way to destroy gameobjects in onValidate in editmode? if I do Destroy, it screams that I must use DestroyImmediate in edit mode as Destroy is not supported, and when I try to do DestroyImmediate, it screams it can't do DestroyImmediate in OnValidate, and I must use Destroy
I'm at a bit of a loss
EditorApplication.delayCallback
seems like something that'd help. Could you give me a hint on how exactly to use it? Unity documentation isn't particularly... verbose
EditorApplication.delayCallback += () => DestroyImmidiate(gameObject);
thanks!
hi ,
1 - is it possible to get image's material with all the CURRENT settings ( ex: if color was red then I should get color="red";) ??
2 - is it possible to not just get the material but read it as a text ?
UI.Image?
yea
do you use custom material on the image?
by default color is the vertex color of the mesh
no, I was just playing around with image and I thought of those two questions , tried to search them myself but i couldnt find an answer
not that important
default behavior is when you set image.color the image mesh generator sets all vertices to that color
which is later rendered by ui shader
so you cant technically get the color from the material since it doesnt use it
as for getting material properties, if image/graphic class allows you to get internal material through material property, you would have to iterate all material properties and write those strings yourself
thanks bro , i took ur advice and moved on โค๏ธ
yo is there a way to make visual studio break on exception? in specific a IndexOutOfRangeException
im trying to debug but its happening inconsistently, reqired input and on something that runs multiple times each frame so I need it to only break if an exception actually occurs
closest thing would just be a try catch
actually u can set conditions on breakpoints, but u need to know whats actually causing the error
ill try a try catch and putting a breakpoint in the catch maybe
i assume u probably know what variable is specifically causing the issue, if u right click the breakpoint u can set a condition like x > array length
I did not in fact i was trying to trace through a call stack to figure it out, but placing a breakpoint in a try catch worked
oh wait yeah i get what you saying i could of also did that
that might indicate u have a lot of things on 1 line, if an error could not indicate to u what variable was causing the issue
honestly ive never used conditional breakpoints before, just remembered hearing about it after i said try catch
So I've got this mesh being generated and rendered 100% on the gpu (sorry for the low res vid) As you can kinda see, the mesh surface normals aren't smooth since its generated with marching cubes by appending triangles to a AppendStructuredBuffer. I'm wondering if anyone knows a good way to detect other vertices that are close by to average the normals with to result in a visually smoother mesh. I'm looking for ideas that can be done without having to transfer the mesh back to the cpu, I want to do this as a pass in a shader. https://i.imgur.com/ZDjXyou.mp4
You will need to have access to the original from the shader. (Which I do not know if possible) It would also probably be inefficient.
Personally I would do the process after the Marching cubes algorithm, in the computer shader.
i was just thinking, maybe i could calculate the normals of the triangle corners by sampling the surface near by rather than using the other triangle corners to calculate the face normal, presumably this would provide a normal that would be more consistent with any other verticies that fall on the same location ๐ค
How would you proceed to sample the "near surface" from a shader without the original mesh ?
im talking where the mesh is generated
And, why can you not make the process in the ComputeShader ?
it would be
Just do an average of the normal of each vertex (That are at the same place)
like this is how i calculate the normals currently for the whole triangle, but if instead
i did something like this, it would be more localized i think
red lines would represet the offset where i sample the noise function
it shouldnt be i dont think
Given that you sample the same vector.
The normal is normally the cross product of 2 vector composing the triangle.
its hard to explain but basically i create the mesh by sampling a noise field, and if i sample closer to the vertex, the noise function should produce more localized results
(For flat shading)
From the look of it, you have the same normal from all your vertices.
currently yes, cus im using the corners of the triangle to calculate the normal
Which result in a flat shading.
correct
however if instead of using the corners i use closer points, i think it will produce normals that are closer to the average between the triangles
If you think that you can somehow extrapolate normal from the noise you use to generate your meshes, then do so. However, from my understanding of Marching Cube, the normal are already defined from the subset of meshes you use.
If my understand is correct, I might be confusing some concept there, you have a subset of a given size of possible meshes which you predefined. Then from the neighbor of your currently processed "cube", you choose the correct mesh.
like if the noise field ground truth is the red line, and the black line is an edge of a triangle, and the current normal is calculated via the triangle corners, it produces the green normals, but if i sample close by the vertices, it should prodice the blue normals im pretty sure
Hiya, this is a bit of a weird question, but I'm trying to find a way to take a total value and compare it to some kind of array of addition tables to work out which values it is made up of. There are 4 specific values being compared, the total value can be made up of anywhere between 1 and 6 of these being picked, and no matter which combination there are no duplicate total values by which I mean there can only be 1 answer.
Example:
Input Total Value: 19.23
Values to compare: 4.08, 4.66, 5.25, 5.83
Result: 4.08 + 4.66 + 4.66 + 5.83 = 19.23
Does anyone have any idea how I'd do this?
Where the values to compare come from ?
Is it the wanted result ?
sounds almost like a homework question, but id prob start with the largest value in the set and subtract that from the total, then keep using the largest until its too big for the final amount and move down until its small enough, repeat this, and if no solution, backtrack and try smaller 1 step up, and repeat (basically a generic backtracking algorithm, similar to what can be used to solve sudoku)
they'd be in the script, those 4 were an example but i'd be using other numbers later so it would need to be changeable
Why can you just not add them up and compare with the result wanted ?
im like 99.99% sure you can solve this with a backtracking algorithm
u definitely can, but this seems like a problem that doesnt need to exist in the first place
(you could also brute force it but that would be very slow in comparison)
It really depends on what the problem actually is.
yeah, imo it seems like a homework question more than a real world problem lol
this does look like a school assignment or leetcode question yea lol
It could be: generate a subset of the given number where it adds up to the given number.
Which is widly different than what you are inferring the problem to be.
That's what I'm trying to figure out how to do, if i input 19.23, i want the program to run like "4.08+4.08+4.08+4.08+4.08" then realise that that's too low and try 4.08+4.08+4.08+4.08+4.66 and repeat until it gets the right number
but i'm not sure if there's a more efficient way than the code version of what is effectively trying to figure out someone's pin xD
you could also likely solve it with a genetic algorithm
tbh even running this as combinations (aka brute force) shouldnt be long
Give a Number X
S <= Randomly sample a number between 0 and the X
Repeat for 0-S and S-X till you get the amount of number you want
Recursively.
That is given that the problem is what I understand it to be.
yeah prob wouldn't take long in most cases just brute force, i agree, though does depend on what kinds of numbers you have to work with
That would be worst way to do it. You can simply add up every number then substract or add the difference to your total.
It does seem like a homework question, for a bit more info on what I'm trying to do, is i want to make a little program for tracking how "good" items in a game are, the items can roll stats and each stat roll will be 1 of 4 values which vary based on which stat is rolled, i want to be able to assess the quality of the rolls and therefore the quality of the item overall, here's an example of the stats, this item has 8 values rolled between these 4 stats.
4.08+4.08+4.08+4.08+4.08=16,32
19.23-16.32=2,91
2.91/4=0.7275
4,8075 + 4,8075 + 4,8075 + 4,8075
Pretty sure they most already be have theory craft for your game.
Is it Genshin Impact ?
i recognize what that pic is from, there is already a site that you can upload screenshots of to and it will rate it for you lol
yeah ^ ^
Seems similar to the โthree sumโ or โtwo sumโ problem, thereโs some great videos out there that showcase it ๐
is there a preprocessor define for when you build your project as a "Development Build"?
but i'm asking here because I want to make something for it, rather than use the websites which don't do it how i want lol
What you are doing is known as TheoryCrafting
might be a good search term that could help find more resources
whoops, found it DEVELOPMENT_BUILD sorry!
oh wait wrong @
To be able to assume the actual quality of the item you must have access to the underlaying equation that made up the game.
@dawn dome
tbh i dont know why you even want to break down a final stat into the things that make it up, when from a power perspective, you can rate it by knowing its final value vs the max theoretical value
Those site has usually made the required work to "guess" the equation.
because you can only know the max value if you know the number of times that stat has been rolled into, a 25% attack roll can be 6 awful rolls or 4 amazing rolls
will check these out, thanks ๐
sure, but if you normalize the final roll against the max roll you can determine how close to max it is. Then just add up the normalized stats and the closer to 1 it is, the closer to a perfect roll it is, but you'd likely also want to weight each stat individually based on the type of stat, like flat attack would be much less "valuable" then attack %, etc, so apply weighting to the normalized values, and bam
Hmm, i see what you mean, I wanted to find the quality of the individual stats rolled though, for starters that would require me to adjust the weighting based on the character it's used for, rather than simply comparing the say current attack to the max attack i could have got in the same number of rolls.
I've not play Genshin Impact a lot, however, from what I remember you did not care about the individual stats value, but its type.
Things like health was not contributing to DPS, thus making it irrelevant.
Anyway, this is not a Unity question nor a code question.
If you want more help, you should consult appropriate resources.
The type is much more important, but that is mostly why I want to figure out what values the total value is made up of, so I can find out how many times Attack or Crit damage were rolled by simply typing it into a field. Finding out the quality of the roll is secondary to what I'm trying to make, but since as far as I can tell having that information is mandatory, I figured it wouldn't hurt to also know whether I rolled 3 worst rolls, 3 best rolls etc
It's not a unity question or a code question when I'm working out how to code it in unity? ๐ค
I guess you could argue since genshin was made with unity, its a unity question ๐คก
I didn't even know genshin was made in unity xD
Just use a table...
Find a good source and make a spreedsheet.
lol ive even had the unity quality selection screen pop up sometimes when launching genshin ๐คฃ
I've done that before lol, I'm figuring out how to streamline the process, if you don't know how to do it that's fine, but it's not very helpful giving suggestions unrelated to coding
The usage of database is definitly related to code. I am simply suggesting you to use the appropriate tool for the job.
if (velocity.x < 0)
{
velocity.x += decelerationSpeed * Time.deltaTime;
if (velocity.x > 0)
velocity.x = 0;
}
else if (velocity.x < topSpeed)
{
velocity.x += accelerationSpeed * Time.deltaTime;
if (velocity.x > topSpeed)
velocity.x = topSpeed;
}
transform.position = new Vector2(transform.position.x + (velocity.x * Time.deltaTime), transform.position.y + (velocity.y * Time.deltaTime));```
Am I multiplying by Time.deltaTime too many times?
Does not seem to be the case.
velocity(m/s) = decelerationSpeed (m/s^2) * Time.deltaTime(s)
position(m) += velocity(m/s) * Time.deltaTime(s)
it is (velocity.x * Time.deltaTime), this would be very small
accelerationSpeed would need to be massive
Ok, so I need to take the Time.deltaTime out of the line?
velocity.x += decelerationSpeed * Time.deltaTime;
The size of the result does not mean anything... This is the correct calculation to not get frame depend
If you do that, depending on your frame rate your acceleration will not be correct
I have a major problem
Also, you will not be able to use real values such as 9.81u/s^2 (Which usually not appropriate in games though)
https://gdl.space/zuzokabuna.cs
I need this code to procedurally generate 50 tiles infront of the player, and destroy 50 tiles behind, it doesn't do that, it just generates 50 tiles
I guess all I can do is follow @buoyant crane's advice on looking into "three sum" and "two sum" problems, since it seems they knew how to do what I was looking for
Move your tiles instead of destroying.
Or use Pooling
it is procedural generation with random gaps between every tile
also waht is Pooling
Object pooling is the concept of creating the object then instead of destroying it when its no longer needed, you store its reference and reuse it later
It will most likely not work on your issue because it is a look up problem. The value are arbitrary and does not follow logic. You simply have to look up the data from a database.
unity now has built in object pool classs to help with pooling
so it won't generate and destroy, it will just move them
What would you suggest I do to fix this. It seems to me that applying it in both places is needed but then I am applying it twice?
You never explained what the issue is...
correct, when you request an object from the pool when there is none allocated, it creates one, but then when you no longer need it you return it to the pool, and instead of getting garbage collected, it sits waiting for you to request another object from the pool, and then its recycled basically
that seems complicated to me
Also, have you consider using Tilemap ? Not exactly sure what your game is.
Wouldn't this reuse the same tiles over and over if its suppose to be procedurally generated
its pretty straight forward, you can picture it as just a simple list of game objects
i believe it can generate on demand, only if the pool is full. If there is an "empty slot" in the pool, it will use that instead of creating a new one. I've never used unitys pool system so I'm not sure if you need to define a fixed size but if not, surely this is the case
I want the character to move frame independent. I also want to do those checks before I apply the acceleration. How can I do both those things and while using Delta Time?
for example
velocity.x += decelerationSpeed * Time.deltaTime;
0 += 1 * .5
transform.position = new Vector2(transform.position.x + (velocity.x * Time.deltaTime), transform.position.y + (velocity.y * Time.deltaTime));
0 + (.5 * .5)
you can add a "init" function or w/e that updates anything you want and call that after pulling an object out of the pool
Think in function of unit like I just did earlier. #archived-code-general message
pool is just a stack (stack implementation is faster than queue)
pop a object when you need it, else push into stack
unity now has a number of built in pool types here is the documentation for one of them. https://docs.unity3d.com/ScriptReference/Pool.GenericPool_1.html
I wouldn't think of a pool as a queue, as queues typically enqueue/dequeue elements and destroy them. Pools can reuse any element whenever possible in any order
that is the shortest scripting doc I have ever seen
pool can be implemented as queue dequeue when you need it
but reallocation of queue is not as simple as stack
i mean the data structure that holds the items in the "pool" is kinda irrelivant to the usage, you technically "could" use a stack or a list or a queue or a dict or w/e other storage container you wanted for the pool, it effectively just needs to store a reference to the items that are available to keep them from being GC'd
granted some structures will be better optimized, but functionall they would all work
Sorry when i read this on mobile, I read it wrong before. The first delta time is making your velocity increase while being frame independent.
The 2nd is whats making your actual movement frame independent.
Although if you are using 0.5, i imagine your increase is quite slow
What do you mean ?
why not just use a list rather than an array... ๐
what is list? linked list?
no, System.List
list is array
list will dynamically resize as needed
(The screenshots are of C#'s internal implementation)
it is just an array with some magic (realloction)
sure, but like i guess i dont get why it really matters, just set some upper bound on the initial size then u dont need to worry about it moving around in memory as it resizes
The amount of memory being allocated would result in the same wouldnt ? I guess it would be a bit less ineffective in the copy, however it should not even be measurable.
if op doesn't know what you suggested before, i think using a list is the safest bet. especially since reference types are simply the c# version of pointers (4/8 bytes per reference) the list allocation size will be negligible
just use unity's built in pool, it has support for a default max size where it reserves the mem for that size, then any requests past that can be handled with normal GC, but ideally u set the max size to be large enough that it doesn't have to switch to non-pooled items
so like if u think 50 is the max, set that, then if it accidently happens to go a bit above 50 for a while, it just GC's the extras and only recycles the max of 50.
the memory allocated is the same, but the time of copying is not the same (pipeline, cache miss, etc)
though i dont suggest a newbie to object pool consider those optimizations unless the allocator affect the overall performance (i have written a poor allocator and suffered from it.....
In this situation, it will be hardly something to consider. The difference also decrease with the amount of objects.
Ye prob not worth using unless you actually see a measurable performance hit caused by allocations since in most situations the slow downs are a result of other suboptimal code. That said I use pooling literally every day at work (in game dev) and if used correctly, they can make a substantial difference in large projects.
queue crew represent
I am getting this error
Assets/Scripts/TurretAuthoring.cs(17,26): error CS0246: The type or namespace name 'Baker<>' could not be found (are you missing a using directive or an assembly reference?)
With this code:
using UnityEngine;
using Unity.Entities;
public struct Turret : IComponentData
{
public float shootSpeed;
public Bullet bulletPrefab;
}
public class TurretAuthoring : MonoBehaviour
{
public float shootSpeed;
}
public class TurretBaker:Baker<TurretAuthoring>{
}```
I do have the entities in my assembly reference, am I missing any other?
Found it, it needs to have Unity.Entities.Hybrid
Performance question
Is there any performance difference between using and iterating though a 2d array[Height,Width] vs a normal array[height*Width]?
I e been using a normal array for a grid system I've been doing but it's just ended up making things more confusing for alot of the time but I also know I iterate through it and use it alot so I Wana know if there would be any real risk of performance tradeoffs
not enough to matter in 99.9999% of the cases. Seems mostly like a permature optimization concern that isnt worth thinking about
have u actually noticed any performance issues? preoptimizing and sacrificing the ability to understand the array is a major loss.
The difference really would be negligible. Except now in a normal array, u would have to calculate what u consider a new row to be.
Yeah. I was actually only using it because the tutorial/thing I was porting to C# (originally in C++) used it
imo store it in a way that makes sense for your use case, if it is a problem that lends itself well to a grid, use a grid
Hey all. So I've got a problem. When I pick up an item I want to get the script attached to the item that is of base abstract class BaseItem. However, I also want to destroy the object, so I can't just take a pointer to the script. I need a way to get a new instance of that particular subclass, except I don't know what that subclass IS.
Ty, Just wanted make sure before I go through the precess of changing all my methods to work with a 2d array instead of an index just for it to kill the frame rate
it would need to be exceptionally hot code path with huge array size to make any potential difference. Imo just use whatever makes sense from an "understanding" standpoint and don't worry about trying to micro optimize before it becomes an issue
It's like at say absolutely Max iterating through say 10 of these arrays which are 64 by 64 each
yeah u wont see any perf issues at that size
U wont notice it even run at this amount
๐
Dont think Unity serializes 2D arrays, but that's not hard to get around
Yeah but I don't need to directly set them at all..via the inspectors I mean
Also for rendering for making the pixels for an texture are you allowed to pass in a 2d array into that or does it have to be a normal array?
your code here is weird and is a ticking timebomb because gameState.curHeldItem is a zombie script. On top of that, downcasting the way you want is typically a code smell
Then what is my option, take the whole game object? And what, de-activate it in the heirarchy?
no, typically you hide the actual implementation between an abstraction (polymorphic base class or an interface). If you care what the actual type of BaseItem is, your abstraction there is faulty
also what is a zombie script bc that doesn't fit my definition of the term
The actual implementation of what?
I don't WANT to care what the actual type is
you set gamestate.curHeldITem to a component on a GameObject, and then destroy that GO. Now the current held item is actually dead, but you're holding a reference to it. Any call that goes to the unmanaged layer (.transform, .name, etc) will throw an exception
I just want to get a copy of the BaseItem component so I can call Use after I destroy the object
Yes, I understand that's the problem it's what I'm trying to fix
Yeah, interface with a use implementation
How will that help me
you make it virtual
I still need to get a copy of the script and that copy has to be the sub type
so it can call the right Use
I don't understand your problem then, if BaseItem has a polymorphic Use method, you can just call it
No, I can't, because I've destroyed the object it's attached to
it's not destroyed until the end of the frame
I want to pick up the item, store it, then later call Use()
This is the pick up code
then why are you killing it? remove the destroy call
Ok so now the item sits on the ground
after I walk over it and hit pick up
Do I say SetActive(false) and just leave it sort of floating there in the ether
Why can't you do this all in one frame?
I don't want to use the item as soon as I pick it up
Ah, well, then yeah you have to store it somewhere then
I want to
Walk over the item
The item object goes away but I get some info from it and store it
Later the player presses the use item button and calls the appropriate overridden function
Character needs some inventory holding script then
Maybe I can take the prefab and then later get the Use function from the prefab's version of the script?
maybe curHeldItem should be a wrapper class around a command that BaseItem generates, that's what my solution would be
really depends on the scope of what "use" would do, like do you need it to be visually displayed again, is it going to be in the characters hand, or is it like a consumable, that you can use a generic animation for like drinking a potion, etc
The items are really simple, like, potion, fireball scroll, and you can only carry one at a time
so I don't really care about having that specific item
if its an equipable item like a gun or something, you could just have one of every gun instance already a child of the character, placed in its hand, and just disable all the ones that aren't currently in use, give them an id or something, then when you "pick up" a gun, add that id to the list of available ones that you can swap to. or if using an item is just applying an effect, you could store a dictionary of actions that could be invoked when you "use" an item, and you could keep a count for how many you have, like for example class Consumable { int count; Action OnUse; public Use() { if (count > 0) { OnUse?.Invoke(); count--;}} } then do something like Dict<int,Consumable> and setup all the possible consumables in a player script and update the count of the consumable if the id matches the pickup. or something along those lines
could use strings as ids instead like inventory["lesser_health_potion"] or enums inventory[ConsumableType.LesserHealthPotion] = new Consumable(() => health += 10);, etc
then when you pick up an item on the ground, call a func like void AddInventoryItem(ConsumableType itemType) { inventory[itemType].count++; } and when you want to use it UseInventoryItem(ConsumableType itemType) { inventory[itemType].Use(); }
you could ofcourse build that out into a whole inventory class and pass in the current gameobject as a parameter into the use functions etc, but that would be a pretty simple way of picking something up that can do various things and having it be "usable"
if you wanted to shoot a fireball, you could add a "Target" parameter to use, and then do something like UseInventoryItem(Consumable.FireballScroll, enemyTarget); and that could be setup something like inventory[onsumable.FireballScroll] = new Consumable((target) => { /*spawn fireball prefab with "move to target" script*/ });
My imported character is in a weird scale, defaults to scale 100 imported in unity. In my starterasset 3rd person controller I set my models scale to 50, but in play mode it gets scaled back to 100. (I can "fix" this by leaving it at 100, and scaling the whole playerarmature by 0.5 but this messes with the character controller settings, and I'd rather just scale the model skeleton. searched the few scripts I'm using for "scale" and can't figure out what's causing this?
this is probably fixed by an export setting in whatever you used to make the model. If its blender, i believe u can apply transforms (or whatever its called) to fix it before exporeting.
Probably ask a channel more related to models though
but is it possible that model import settings cause it to rescale at runtime?
I have no clue. You'll want to ask the people who actually know this stuff, not in the code channel
@lean sail I don't want to mess with the model, I can insert a scaling empty parent in my player armature above the skeleton, but then it seems the animator doesn't pick it up
https://hastebin.com/share/cibifosaho.csharp
I have a server-side zombie set up and for some reason it isn't moving at all. If i multiply the chracterController.Move it does move but very stuttery and strange.
Im using mirror, same* as unet
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i was wondering if anyone knows how to enable and disable sprites and buttons from different scenes when colliding with an object in a different scene
good morning
Hopefully a quick question.
I have a web app that uses TypeScript for typings on the front end and on the node API. I'm thinking of making a unity version but I don't want to lose my library of types.
Is there a way to import typescript types into the C# environment of Unity?
The languages are so different that I doubt there's even a semi-automated way to do that
I anticipate a lot of the typescript specific things would have to be simplified down to their most approximate relatives, even if it's not already been done, I'm hoping there's a way to import .ts files and interpret them when building or something similar.
Before I go down that rabbit hole I thought I'd ask in case anyone else had a similar situation.
Idk about the topic but did you try googling already? 'import typescript to c#' seems to find many articles that seem fine if i understood your problem correctly(?). Might be good start to look at those
I wrote this health code but the health doesnt lower on collision with enemies
first compare tag with CompareTag("yourTag") method
does collision even happen?
Try writing "OnCollisionEnter2D" correctly
haha, yeah
if that doesn't help, put debug messages outside the if block
collision happens but the log doesnt appear on the console
Ill try comparetag
Ill switch the projectile colliders to triggers
U sure all objects have necessery colliders with right sizes
yeah
And atleast other object must have rigidbody2d
..I wrote "player" here ignore that
yeah
I am aware
woo! it works now!
the player character can now fucking die, thanks uwu
Wooo
Blud said uwu
๐
OwO
So what lmfao
fr
So. Anime people are weird
wha?
And its cringe
Im confused lmfao
Anime talk in programming channel, crazy
is there any way to undo all Physics.IgnoreCollision calls?
i want to make bullet instancing and i don't want to associate bullets with certain colliders/objects/factions. I don't want them to keep ignoring the old colliders after they get fired again

Fr
@limber agate Keep it on topic, please
death to cringe culture :3
I was just saying its cringe but no problem mb
Hellu hellu I created a new project and added a map from the unity asset store (dunno if that's related to the problem), anyways somehow my gravity settings are reversed so +9.81 is falling and -9.81 is somehow floating up in the air pls help 
would using rb.velocity instead of rb.AddForce prevent my character from sliding?
cope
it's the same
darn.
it just prevents accelerations
if you're talking about slopes, you should disable unity's gravity and calculate it for yourself
velocity prevents that?
not slopes
regular ground
addforce calculates acceleration, velocity dictates the current velocity
and yes, sliding around is in part, acceleration, so if you use rb.velocity you will prevent sliding around. since you don't accelerate and suddenly happen to stop
Well, kinda. You can use Physics Materials to prevent sliding But your player will also stick to walls
want to add that alot of games actually use rb.velocity instead of rb.addforce
my current movement code is this but this results in, I guess some weird movements? I think I wrote somethning wrong-
There are ways to make wall colliders exempt. You need to check for corner cases and change behavior.
To this mostly. Also can have separate wall coliders without friction.
AddForce is good for realistic controllers but also requires some more code in order for it to properly work
With AddForce you gain velocity, meaning you will keep it when you stop giving input and thats good for when youre in the air for example. But in order to keep the player from sliding youll need to do some sort of speed control like this
Vector3 flatVelocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
if(flatVelocity.magnitude > moveSpeed)
{
Vector3 limitedVelocity = flatVelocity.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVelocity.x, rb.velocity.y, limitedVelocity.z);
}
Yeah, but I usually dont do that because that makes the controller too dependent on the map
Okay um- tryint to understand that code now--
You can completely remove the if statement im pretty sure, whats moveHorizontal
can also check collision direction and turn off friction if collision is to "wall-like" structure.
moveHorizontal = Input.GetAxisRaw("Horizontal");
the if is preventing you from stopping
if moveHorizontal is 0, you don't change the velocity, so you'll keep moving
- Get the players current velocity (
flatVelocity) - Check if the magnitude of the player is above the move speed (my input is Input.GetAxis(". . .") * speed * speedMultiplier)
- If it is, set it back to normalized flatVelocity (I dont remember how that part works lol)
But basically just making the speed not go overboard
You dont need to do this for Velocity movement, this is for AddForce
Yeah, you can remove the if statement then
?
i think our dude is in 2d, so
vector2 velocity = rb.velocity // assuming it's rb2d
or just use rb.velocity directluy
Yeah, Im using 2D
Yeah just replace all Vector3's with Vector2's (if youre ever gonna use it at all)
try it, also no need for the 0
But its a vector 2 value so I do kinda need that 0
i can smell this will cause you some problems in the future (especially when you try to add falling)
try:
rb.velocity = new Vector2(moveHorizontal * moveSpeed, rb.velocity.y);
Yeah falling got all messed up
Oh nvm, I thought I saw something else
I am
Very confused- Im sorry-
Dont use that code since youre doing very simple Velocity controller
using force for movements is good for keeping momentum too
I was just talking about more complex controllers
Yeah, thats why its way better for more physically realistic games
because i can work for the character to move by force and i can change the velo based on whatever i want
Okayy, theres no more sliding now!
Hm.. Idk if it feels too snappy rn. Eh, I dont have problems with it atm.
Yeah, very simple 2D movement system
are you doing input.getaxis?
then the stopping should happen instantly
It does
Now add a physics material to it with 0 friction, this is so it doesnt stick to walls, is still wont slide though, theres different ways to make it not stick as FogSight said but for this a physics material is good
Already did that material!
:>
oh alright good
Thanks y'all ^^
I made this 2D Rigidbody AddForce based controller a while ago, you can try it if you want, but I dont know the best values
Wait
There, the jumping is probably weird, I didnt finish it
How do I make a grid layout that only expands downwards?
Currently if I force 4 elements in a column and add 5th element it will push the previous 4 elements up.
ah
Child alignment upper left fixed it -,-
This method seems to make infinite spawning after changing _textComponent 2nd or 3th time
private void Update()
{
if (_textComponent.textInfo.lineCount > _textComponentLineCount)
{
int firstCharacterIndex = _textComponent.textInfo.lineInfo[^1].firstCharacterIndex;
string lastLine = text[firstCharacterIndex..];
text = text[0..firstCharacterIndex];
textComponentIndex += 1;
//_textComponents[textComponentIndex].text = lastLine;
text = lastLine;
print($"; lastLine: {lastLine}");
}
}
private int textComponentIndex
{
get => m_textComponentIndex;
set
{
if (value < 0) return;
while (_textComponents.Count <= value)
{
TMP_Text newTextComponent = Instantiate(textComponentPrefab, textComponentsHolder.transform);
_textComponents.Add(newTextComponent);
}
m_textComponentIndex = value;
_textComponent = _textComponents[value];
_caretPosition = (text == "\u200B") ? 0 : text.Length;
AlignCaret();
}
}
Is _textComponent just not set quick enough?
everything works if I delete this line:
text = lastLine;
also it enters infinite spawning when firstCharacterIndex stats being 0
Actully I should ask why is TMP_Text.textInfo.lineCount == 4 and TMP_textInfo.lineInfo.Length == 8 ?
they both should be 4, shouldn't they ?
- I have a list of objects that serve as wrappers on top of strings, and array of strings to insert into the list. Is there a linq query or whatever way to do this other than manually iterating?
ForEach?
you can extract the strings into new collection with Select i think
then ToArray
anyone knows why vs-code hates this snippet?
foreach (MonoBehaviour script in child.gameObject.GetComponents<MonoBehaviour>())
{
if (!(script is SpriteRenderer))
{
script.enabled = false;
}
}
even though it works as intended, it warns me about "The given expression is never of the provided ('SpriteRenderer') type"
ay, you're correct
they should have checked the docs first
Hello.
Guys i have been trying to handle this bug in prints.
So the character is not fixing to the character controller, and i have tried to deactivate everything for testing purposes and that still happening
no, agreed. i was too quick to answer instead of leading them to it, so i removed it . . .
can anyone help here?
Revisiting a project, this seems to be way out of my depth and it won't let me run the game? Any help would really be appreciated, no idea why this has happened
Backup your project files.
Close Unity, navigate to where the project is, and delete the Library/ folder.
Restart Unity, it'll take longer than usual because the folder will be regenerated.
Thankyou so much you're a life saver!
yo how do you Compare two vector2 ints when sorting a list of them?
movementQueue.Sort((a, b) => a.endPosition.<idk what goes here> (b.endPosition));
before they were 2 ints and i was just using CompareTo
is there no eqivalant for vector2Int?
you'd compare the x value of both or the y value if the x are equal: a.x.CompareTo(b.x) . . .
ah, actually never mind due to some changes i made to the code i dont actually need to sort this lol
just Sort doesnt work?
what type is a ?
it prolly (should) has a default implementation . . .
Guys, I have a prefab for my pause screen and options screen. The script that controls the Pause UI is attached to the main Canvas game object. Everything works fine, but when I change scene and Instantiate the Pause UI prefab, it creates two. When the 3rd scene loads it then creates 3. It's like the Pause UI script isn't getting destroyed on load, even though I'm not uses Don't Destroy On Load... anyone come across something like this before?
when you change scenes do you already have a Pause UI in it?
I'm creating a tool. I want someone else to design the UI in a prefab.
got a load of new errors and none of the textures are there?
show code where you instantiate it
Im not sure what kind of problem u mean. Do you want to stack those rotations or ignore another. Anyways the usual solve to problems like this ive done, is to make player object not have sprite renderer, and just have the code stuff, and have yhe player object have child with spriterendereers and animations
The Pause UI script, yes. If I have a scene where I want the Pause Screen to be usable.
Then they dont break/step onto each other atleast
Sorry for the noobness, but how do I post code directly in the discord channel?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
You had errors in your code when you exited the app. Fix them, and exit Safe Mode to trigger the reimport
okay thankyou
private void Pause()
{
if (isPaused)
{
ClosePauseUI();
}
else
{
if (PauseGO == null)
{
if (OverlayGO == null)
OverlayGO = GameObject.FindWithTag("UI-ROOT");
PauseGO = Instantiate(UIUtilities.GetPauseUI(), Vector3.zero, Quaternion.identity);
PauseGO.name = "PauseUI";
PauseGO.transform.SetParent(OverlayGO.transform, false);
}
ClearButtons();
isPaused = true;
canSelect = true;
Time.timeScale = 0;
}
}
is OverlayGO DDOL?
No
OOOOOOOOOOOOhhhhhhhhhhhhhh
That might be it
Sorry guys, I'm a dummy. Pause is called from an event thats fired in the input manager. I've been making changes to the input system and I edited out the line where I unsubscribe from the event. Let me try that.
Yep, that was it. I'm an idiot...
Thank you @ashen yoke
not a code question #๐โart-asset-workflow
wrestling with poor KCC architecture here
the whole thing is controlled by KinematicCharacterSystem
KCCMotors register in it
but no collisions are detected if the KinematicCharacterSystem is not in the same scene as the motors
when i drag it to the scene with motors at runtime they start working
actually no it deletes itself
anyone has clues as to why overlap methods can fail in multi scene scenario?
pretty sure each scene is a separate physics scene
but Physics api is static
oh actually i may be wrong, based on the docs scenes should just use the default physics scene unless otherwise specified
https://docs.unity3d.com/ScriptReference/Physics-defaultPhysicsScene.html
๐คทโโ๏ธ
hey, can i optimize that code?
private string EncryptDecryptData(string _dataToEncrypt)
{
string result = "";
for (int i = 0; i < _dataToEncrypt.Length; i++)
{
result += (char)(_dataToEncrypt[i] ^ encryptionKey[i % encryptionKey.Length]);
}
return result;
}
that is O(n^2), use a string builder and reserve _dataToEncrypt's length. Probably can't do better than that unles you want to do unnecessary multithreading stuff
well turns out if you specify LoadSceneParameters.localPhysicsMode when loading scene additively it will create a new physics scene, even tho there is zero mention of that anywhere here https://docs.unity3d.com/ScriptReference/SceneManagement.LoadSceneParameters.html
private string EncryptDecryptData(string _dataToEncrypt)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < _dataToEncrypt.Length; i++)
{
result.Append((char)(_dataToEncrypt[i] ^ encryptionKey[i % encryptionKey.Length]));
}
return result.ToString();
}
``` that?
if you really want to optimize it look into ZString
yes, and since you already know how many chars will be in there, init SB's capacity
what do you mean? by init SB's capacity?
StringBuilder result = new StringBuilder(_dataToEncrypt.Length);
thks and that s really faster?
it will avoid some unnecessary copying, so yes by probably a negligible amount overall unless you're cramming tens of megabytes+ through this encryption method
public void GenerateChunk(Vector2Int chunkLocation)
{
MapChunk chunk = GetChunkDirect(chunkLocation);
int sbaseHeight = 20;
int sheightMod = 15;
int gbaseHeight = 15;
int gheightMod = 4;
int waterHeight = 25;
float scale = GameLogic.i.pnScale;
int[] surfaceHeightOffsets = GetHightOffsets(sbaseHeight, sheightMod, scale, chunkLocation.x, chunkLocation.y);
int[] stoneHeightOffsets = GetHightOffsets(gbaseHeight, gheightMod, scale, chunkLocation.x, chunkLocation.y);
for (int x = 0; x < MapChunk.chunkSize; x++)
{
for (int y = 0; y < MapChunk.chunkSize; y++)
{
int surfaceHeight = surfaceHeightOffsets[x];
int stoneHeight = stoneHeightOffsets[x];
if (y <= surfaceHeight) { chunk.SetCell(x, y, new Sand()); }
if (y <= stoneHeight && y <= surfaceHeight) { chunk.SetCell(x, y, new Stone()); }
if (y <= waterHeight && chunk.GetCell(x, y) == null) { chunk.SetCell(x, y, new Water()); }
}
}
}
public int[] GetHightOffsets(int baseHieght, int maxMod, float scale, int chunkX, int chunkY)
{
int[] Offsets = new int[MapChunk.chunkSize];
for (int x = 0; x < MapChunk.chunkSize; x++)
{
float xcord = (float)x / MapChunk.chunkSize * scale + xNoiseOffset + chunkX;
Offsets[x] = Mathf.RoundToInt(baseHieght + (maxMod * Mathf.PerlinNoise(xcord, yNoiseOffset + chunkY)));
}
return Offsets;
}```
y and x NoiseOffset are set to a random number on start so why is result always the same?
wait nm i think i was accidentally calling this before i actually set them
this is supposed to "search" for this pair of components (input and centipede)
problem is i don't know if this "tool" is going to be a child of the centipede (which has the input and the centipede components)
or a child of a child
is there some function that will search all parents (until there is no parent) for a component?
GetComponentInParent is a thing
omg is that not for the immediate parent only?
https://docs.unity3d.com/ScriptReference/Component.GetComponentInParent.html
Gets a reference to a component of type T on the same GameObject as the component specified, or any parent of the GameObject.
it does search the object you call it on first then goes up the chain of parents until it finds the component
dude i really need to set some time apart to just read all the functions
so often i feel like i'm reinventing the wheel
a way worse wheel too
dude how many times do you need to be told?
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
read the last line
this is general for crying out load . . .
mesh collider zero bounds in editor, convex has proper bounds, concave zero
whats up with that
Physics.SyncTransforms();
called before ops
seems like the mesh has holes
TMP_Text.textInfo.lineCount is the number of visible lines based on the size of the text container and the content. if your content is bigger than the container, it will continue the text on a separate line and add to line count (even if the original text does not use a new line character)
TMP_textInfo.lineInfo is an array that holds information about each line. its Length is increased in memory to ensure capacity. it will double its length when the lineCount value is greater than its current length. at any point in time, does your lineCount surpass 4?
Hiya! Would just like to say thanks a ton for the advice last night, you were right on the money, a Combinaitonal Sum backtracking algorithm was exactly what I needed for my program ^ ^ โค๏ธ
how do I make this ball not be stuck and just automatically pop away from the tilemap edges?
it doesn't
probably it shouldn't
but I think it does not, I have checked it
it's just 4
though I wonder if my issue is caused, because _textComponent cannot be changed quick enough in Update()
that's why I am now going to make a coroutine that doesn't allow to type in custom Input Field when changing the line too
i would attempt this first. even when editing the text, if the lineCount does not exceed lineInfo.Length, that array will not update โ allocate more memory โ and increase in length . . .
are you sure?
lineCount does never exceed lineInfo.Length
I am a lil bit confused
visually the text never displays on more than 4 lines, that's weird?
no, lineCount cannot exceed lineInfo.Length
it's always less of equal
you have mentioned it, haven't you?
Anyone know why orbiting it vertically breaks it? I am using an empty gameobject at the position of the sun and rotating it while the planet is the child of that said gameobject. This script is attached to the empty gameobject:
no, it can, and when it does lineInfo.Length will increase its memory. if lineCount changes from 4 to 5, lineInfo.Length will change from 4 to 8 doubling its memory . . .
use AES for more advanced encryption (https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aes?view=net-7.0)
i brought this up last time they asked about this, lol
Doesnt even have to be AES, just using anything other than self made encryption
but I still don't get what does checking if the lineCount does not exceed lineInfo.Length bring?
cause I now get this
Asked there and nobody could solve it
i should've clarified if it exceeds the current lineInfo.Length bcuz if it does then it will change (double) its capacity . . .
that shouldn't be
do I have to prevent it from doubling its capacity?
you can't it happens internally to ensure there is enough space for each line created . . .
U realize your scripts (a component) can GetComponent right?
yeah
So what can I do if I can't control it? So I check if the lineCount does not exceed lineInfo.Length and if it does then ..?
you can store lineInfo.Length in a variable every time the text is updated and log that along with lineInfo.Length. the easy way is to just log lineCount and lineInfo.Length and see when either value changes. i do this . . .```cs
Debug.Log($"Line Count: <color=cyan>{_textField.textInfo.lineCount}</color>");
Debug.Log($"Line Info Length: <color=cyan>{_textField.textInfo.lineInfo.Length}</color>");
You should probably try rotating this point manually and seeing how it affects the dot. I dont think it's broken, I think it's just almost aligned with the axis. Hard to tell with no depth perception
I just realised you can print with colors.
I thought that's just in TMP_Text
always. makes debugging readable . . .
no, I haven't even thought about it.
yeah, it does.
everything worked nice unitil 8th _textComponent
that's what has happpened
it has changed 9 _textComponents at the exactly same time
or 8
it shoudn't though.
I have coroutine.
I don't see any reason why it can happen
private string text
{
get => _textComponent.text;
set
{
StartCoroutine(SetTextHelper());
IEnumerator SetTextHelper()
{
yield return new WaitUntil(() => _setTextCoroutine == null);
_setTextCoroutine = StartCoroutine(SetText());
IEnumerator SetText()
{
if (value == null)
value = string.Empty;
value = value.Replace("\0", string.Empty).Replace("\u200B", string.Empty);
_caretPosition = value.Length;
if (value.Length == 0)
value = "\u200B";
_textComponent.text = value;
_textComponent.ForceMeshUpdate();
AlignCaret();
if (_textComponent.textInfo.lineCount > _textComponentLineCount)
{
int firstCharacterIndex = _textComponent.textInfo.lineInfo[^1].firstCharacterIndex;
string lastLine = text[firstCharacterIndex..];
text = text[0..firstCharacterIndex];
textComponentIndex += 1;
text = lastLine;
Debug.Log($"Line Count: <color=cyan>{_textComponent.textInfo.lineCount}</color>; Line Info Length: <color=cyan>{_textComponent.textInfo.lineInfo.Length}</color>");
}
yield break;
}
}
}
}
Anyone got any ideas on how to debug what is moving my transform? I have one script which is instantiating a gameobject in frame one. At the end of Start in the script that instantiates the object, I print out the position of the instantiated object (first line in img). In Start on a script on the instantiated object, I then print out the position (line 2 in the img), and the position is now different. I have absolutely 0 idea what is moving it. I looked for data breakpoints, but that only works with .net 4 in Rider ๐ฆ
what is the position from the inspector?
(0 0 0), that's the issue
I tshould be the first thing I print
But something is moving them to 0 0 0
hmmmm any thoughts on this one:
Severity Code Description Project File Line Suppression State
Warning CS8032 An instance of analyzer Unity.MonoScriptGenerator.MonoScriptInfoGenerator cannot be created from C:\Program Files\Unity\Hub\Editor\2022.3.2f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll: Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.. Assembly-CSharp-firstpass C:\Program Files\Unity\Hub\Editor\2022.3.2f1\Editor\Data\Tools\Unity.SourceGenerators\Unity.SourceGenerators.dll 1 Active
You see that the first position is being printed correctly
But then they're being moved by something
how are you getting the positions from code?
Dude it's not a problem of getting the right position
I know it's being spawned correctly
But something is moving them
yeah, but we don't know that. we can't assume anything. we need all the info to help solve the problem . . .
your code will obviously help with that . . .
Debug.Log($"Gen {GameObject.Find("Octopus(Clone)").transform.position} frame {Time.frameCount}");
Just to confirm, is it actually moving visually?
If so, I'd just start by removing scripts from the object to see which is the culprit
How can I implement fog of war in a voxel game?
Define a boolean field for each voxel named IsVisible and by moving characters (npcs) set them as visible voxels?
public void DrawWorld()
{
disptext = new Texture2D(MapChunk.chunkSize, MapChunk.chunkSize);
Color32[] colors = new Color32[MapChunk.chunkSize * MapChunk.chunkSize];
for (int x = 0; x < MapChunk.chunkSize; x++)
{
for (int y = 0; y < MapChunk.chunkSize; y++)
{
int colorpos = x + y * MapChunk.chunkSize;
colors[colorpos] = BGC;
Element element = GetCell(x, y);
if (element != null)
{
colors[colorpos] = element.color;
if (element.asleep) { colors[colorpos] -= new Color(.5f, .5f, .5f, 0); }
}
if (overlayColors[colorpos] != Color.clear)
{
colors[colorpos] = overlayColors[colorpos];
}
}
}
Array.Clear(overlayColors, 0, overlayColors.Length);
disptext.SetPixels32(colors);
disptext.filterMode = FilterMode.Point;
disptext.Apply(); // Apply changes to the texture
// Set the pixels of the texture using the extracted colors
display.texture = disptext;
}
this is a script i have for drawing a world but its very laggy any thoughts on possible optimization?
No, the problem is that it's being instantly teleported between 2 different Start calls in the same frame
As the screenshot shows, its the same frame. But 2 very different positions on the same object
do you provide a position when instantiating the GameObject?
this runs on each chunk(basically a 64x64 2d array) in my gameworld world (currently about 6) and is killing framerate
Yeah, that is the first and correct position that is logged.
#if UNITY_EDITOR
GameObject obj;
if (!Application.isPlaying)
obj = UnityEditor.PrefabUtility.InstantiatePrefab(prefab, transform) as GameObject;
else
obj = Instantiate(prefab, transform);
#else
var obj = Instantiate(prefab, transform);
#endif
obj.transform.position = spawnPosition;
6ms?
Use job system
for each chunk
What size does your world have?
As I've said, the first position is correct, so the spawn position is as I want it. But something is moving it inbetween
I just want a way to debug what is moving it
I already tried disabling all scripts on the object
No change
It was taking around 32ms per chunk but holdon my PC just crashed so I'll get back to this in a little bit
What size does your world have?
how do you perform a Ctrl+Z from script?
Like how can i trigger an Undo to take action ๐ง
press ctrl && press down Z
but im not using keyboard
the point is binding to gamepad
Are you trying to implement undo
i have it implemented with keyboard
Or are you trying to implement keybinding
use the command pattern to store actions in a stack if you mean in-game commands . . .
The problem is to implement undo behaviour or input action binding?
triggering undo without using CtrlZ
If you use new input system, it will be really straightforward
i do
i tried looking for CtrlZ and its not there (Actions)
but how do i call whatever process gets called when you press CtrlZ?
because i have the callback that reads the undone data, but if i call it directly nothing is undone (it just re-reads oc)
i've seen this several times
i'm unclear on what causes it, though
it doesn't seem to stop analysis from happening
I appear to be getting an error on the StartCoroutine line. Any idea why? (and yes there's a reason I'm making printf a coroutine, I'm not crazy)```cs
public void printf(string text, params object[] formatting)
{
StartCoroutine("_printf", (text, formatting));
}
...
private System.Collections.IEnumerator _printf(string text, params object[] formatting)
{
yield return null;
}```
Trying to do it similar to the c printf where you pass in a string + any number of other args (including 0) of various types and it uses the format specifiers to put them in the correct places
Don't use string based one
Do StartCoroutine(_printf(text, formatting));
yes, just invoke the method and pass the result to StartCoroutine
you might be thinking of how you can't just put a method directly into Invoke
(which always takes a string)
this syntax
StartCoroutine("_printf", (text, formatting));
is not this
public Coroutine StartCoroutine(string methodName, object value = null);
Not sure how you came by it
ah, true, didn't spot that
it was UnityEditor.Undo.PerformUndo()
same error, even with this syntax (I get this error both with printf("Hello!"); and printf("Hello!", 0); so it's not like leaving the 2nd arg empty is the issue
dont think you can use params in a Coroutine
aight, lemme try a few things and I'll get back to you
Is your script on the scene?
If that is the error it sounds like you are doing something like new MyMonoBehaviour()
does anyone have a script for some procedural generation of low-poly-ish terrain
Does anyone have any code for a farm system such as adding seeds and water and waiting for them to grow
Annd did you attach that script with game object on the scene?
I don't believe this script is attached to a GameObject at all. It's part of a plugin
That's not gonna work. Game object is necessary if you want to run coroutine.
You might look into C# Task instead.
MonoBehaviour shouldn't be used without GameObject
You could probably find one on the asset store (not sure if it would be paid or free), or maybe a tutorial on YouTube, altternatively, why not make your own? Is there a certain step in that system that your confused on how to implement?
I know people've used coroutines in plugins before. Not exactly sure how to plugin loader handles em. It could attach them to a GameObject. Is there any way to check?
from a different plugin https://github.com/Permamiss/HFF_SpeedTools/blob/master/HFF_SpeedTools/SpeedTools.cs ```cs
public void DebugMessage(string theText, float amtSeconds = 2.0f, bool logIt = true)
{
if (logIt)
Shell.Print("<#00AA00>SpeedTools></color> " + theText);
else
{
amtSeconds = System.Math.Max(amtSeconds, 1.0f); // any less may cause the game to lag
StopCoroutine("ClearMessage");
renderDebug = true;
debugText = theText;
StartCoroutine("ClearMessage", amtSeconds);
}
}
private System.Collections.IEnumerator ClearMessage(float seconds)
{
yield return new WaitForSeconds(seconds);
renderDebug = false;
}```
^ uses coroutines
i didn't ask for code
class extends from BaseUnityPlugin which extends from MonoBehaviour
i need the way that i can make it to make my own
I want to know how it works and what is its principle
i need to make it like a simpel stardew valley
Then it sounds like you missed some step that you should follow
Probably somewhere in their documentation?
@lunar hornet This is a channel for code questions, and you already got an answer here. <#archived-game-design message>
ok thanks for your time
Can somebody help me please? My unity editor crashes when the function reaches DestroyImmediate.
The function supposed to create or edit children (A simple mesh plane) of a game object according to an array of structs, and if there's more children than entries in the array, to trim the children.
#if UNITY_EDITOR
private void OnDrawGizmos()
{
//If I check this parameter in the Inspector, editor runs the function once.
if (DEV_UpdateBkg)
{
DEV_UpdateBkg = false;
PopulateBackground();
}
}
#endif
internal void PopulateBackground()
{
if (bkgParent.childCount > bkgLayers.Length)
{
int excess = bkgParent.childCount - bkgLayers.Length;
if (excess > 0)
{
DevLog.Log("bgP: "+bkgParent.childCount+"bgL: "+bkgLayers.Length+"excess: "+excess );
for (int i = 0; i < excess; i++)
{ bkgParent.GetChild(excess).gameObject.SetActive(false); DestroyImmediate(bkgParent.GetChild(excess).gameObject);
}
}
}
foreach (BkgImageElement layer in bkgLayers)
{
for (int i = 0; i < bkgLayers.Length; i++)
{
if(bkgParent.childCount > i && bkgParent.childCount !=0)
if (bkgParent.GetChild(i))
{
UpdatePlane(i);
continue;
}
CreatePlane(i);
}
}
}
Alright update. The main class extends from BaseUnityPlugin. Running the code as a part of that class works beautifully (Hooray!), which is what the code in the GitHub repo does. In my case, I don't want the coroutine to be part of the main plugin class, but instead from different class. That's definitively where the issue lies, not in any of the "optional argument"/params keyword stuff. Imma look at Task and at the plugin documentation some more
Sounds right. Good luck!
Guys how can i make a 3d character jump trough a barrier with parkour animation, instead of normal jump?
Like if i press space i jump normaly.
But when the object forward is not tall enough and the character is running i want to jump with another animation i have.
Problem is that i dont know how tall is the part of the object im trying to jump into, in order to add specific velocity.y
Is this script for editor?
Yes, it's called inside the game object I'm managing children of.
Are you sure bkgParent.GetChild(excess) is not out of bound?
That's the new iteration, before that I tried to just delete all children by for-looping through bkgParent.childCount - it crashes as well. This iteration yeah it isn't out of the bounds, if I comment the destroy line it runs bkgParent.GetChild(excess).gameObject.SetActive(false); successfully
Yup, the BaseUnityPlugin is attached to the BepInEx_Manager GameObjectcs Shell.print(mods["org.bepinex.plugins.humanfallflat.textgame"].Instance.gameObject);
You should know that
bkgParent.GetChild(bkgParent.childCount)is out of bound.DestroyImmdediatechanges child count which is bound
got it working
it was stupidly simple
Main.instance.StartCoroutine(_printf(text, formatting));```where `Main` is my `BaseUnityPlugin`
Well, it still crashes even with this version:
internal void PopulateBackground()
{
for (int i = 0; i < bkgParent.childCount; i++)
{
bkgParent.GetChild(0).gameObject.SetActive(false);
DestroyImmediate(bkgParent.GetChild(0).gameObject);
}
for (int i = 0; i < bkgLayers.Length; i++)
{
CreatePlane(i);
}
}
Can you use breakpoint and see how are the values before crashing?
How would I do that?
Im making an android game, I am trying to figure out the best way to do look input, I think personally 2 sticks dont really work in my case so how can I take looking input in a better way than in that of another joystick?
wait am min, some games dont have a second stick, the one half of the screen acts like a touch pad, how would one do this?
you are looping but you dont use i
nevermind i see the idea
@thin hollow try this one
public static Transform DestroyAllChildrenImmidiate(this Transform tr, bool onlyActive = false)
{
for (int i = tr.childCount - 1; i >= 0; i--)
{
var c = tr.GetChild(i).gameObject;
if (onlyActive)
{
if (c.activeSelf)
GameObject.DestroyImmediate(c);
}
else
GameObject.DestroyImmediate(c);
}
return tr;
}
never crashed for me
ok, so i am using the new input system, i made 3 raw images, they all have the On-screen button component and are maped to the path that should do their function, the jump button works, but I cant for the life of me get the others to do anything
also for testing sake i did do cs if (pause.WasPressedThisFrame()) { print("something"); }
and this still showed nothing
Start logging the methods after input
say i had pause mapped th the path start [gamepad]I had it the same on the component but like I said not even that in update did anything
When you say on-screen button, are you just assigning a UI button event to a method
and if so, check if raycasting is being blocked
no with the new input system there is a script or component of sorts that i put on a raw image that said On-Screen Button you put the path you want it to take the place of and it puts in its value there
im not using the ui button
Ah, ok not that familiar with those but seems just like it binds other control devices besides touch/mouse to the event system
yes, I have one for jumping, it works just fine, but the other 2 dont
Other button input doesn't seem to work either with it?
there all set up the same, just one works
ok, i have no idea now, i changed jumps input to pauses, south to start
Try changing pause to your jump key
and now it worked
ima just duplicate jump and remap the duplicates
ill let ya know if that works
could be just not recognizing the input would be my best guess
i know what the problem is when ever i do shift alt than do the top right corner to snap the images there it dosent work
but they do if there snapped to the side like jump was
thats very odd, but hay i did fix the issue
thanks for your assistance
new discovery, its not the snap position its i think hight
or maybe just being in the corner
ok... final conclusion...
the buttons only work in a select few spots
now all I have to do is find those spots and pick the ones that make the most sence for the button to be in
ok... last time...
it was because the input was on a seperate canvase
this is my final conclusion

Hm... Nope, crashed again. (Also why did you put "this" in the variable definition? It registers as an error)
its an extension method
sometransform.DestroyAllChildrenImmidiate();
if this crashes this is not the culprit
not this method, it can be anything before it, or during it, like some code in OnDestroy/OnDisable in the objects you are destroying
waht are these blurry images supposed to show?
hjow are we supposd to help with this
we don';t even know what the issue is
that si so vague as to be meaningless
you have only shown about 1/3 of the setup involved in making that work
you have to also show your code and how you hooked the code up to the input stuff
Visual Studio or VS Code
no control schemes checked for the XR button
put it on all
also this is a different action
from the "Space" action
your action names are quite confusing too - they shouldn't be named after buttons
but anyway - you'd again have to show how you hooked this up to your code
because for all I know you just didn't hook this up but you hooked up the space one
looks like you have an error in your console
why not fix it :p
juist update or remove that package
that would annoy the hell out of me
#๐ฅฝโvirtual-reality is probably the best place to ask
especially if this not really not a code issue
you cxan and should also use the input system input debugger
so I finally made my game for android, I have one issue though, I want a 16:9 aspect ratio i put it to legacy which i heard is 16:9, but on my phona after the apk was installed i saw the background behind the canvas which i needed in world view for something , how do I make my game only show 16:9 and not whatever my phone decoded to use
not really a code question
How would I import a font (using C#) without it being a system-wide installed font? Running cs Font exampleFont = new Font("C:\exact\path\to\font.otf");Doesn't seem to work
which is what this post from 2020 seems to suggest https://forum.unity.com/threads/howto-load-ttf-font-files-at-runtime.894244/
no mentions of otf there
No, but the Unity docs explictly mention that Unity can work with both ttf and otf files, so I don't see why it would treat them differently in this case
youre testing in build?
I'm working on a plugin, which is why I need to load my assets during runtime via scripting. I launch the full game every time I go to test. I am not working through the Unity editor, only Visual Studio
Here's a whole bunch more info: #๐ปโunity-talk message
I am doing object pooling, and when I wrote ObjectPool I got this error
The type or namespace name 'ObjectPool' could not be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]
That sounds hyper annoying and a huge lost of productivity...
See the following for your question
https://docs.unity3d.com/Manual/class-Font.html
I've read that. Hasn't helped, unless there's something I'm missing
Are you using UnityEngine.Pool;?
Good idea
says "name" not path and no mention it creates anything from that path
2020?
I am using the version before the latest
I think I might see the error
yep, forgot to add a type
!code
๐ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
do you know how to fix this?
Cannot implicitly convert type 'GrassPooling' to 'UnityEngine.Pool.ObjectPool<UnityEngine.GameObject>' [Assembly-CSharp]csharp(CS0029)
You did not implement correctly the singleton pattern.
what is that
public static ObjectPool<GameObject> instance is of not a GrassPooling.
What you tried to do with instance.
what should I do
I looked at the first result and don't know what I have to do
You cannot possibly have looked through the whole page in that amount of time.
I read fast
This is impossible that you have read and understood completely the page. Otherwise you would not be asking the question.
I guess I only looked at the start
Also, the error you have is trivial. If you want the quick fix is to change the type of the object at line 7 to GrassPooling.
However, you should take your time to correctly understand the Singleton Pattern and implement a better variation.
Here is my current implementation for Reference:
using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour
where T : MonoBehaviour
{
private static T instance = null;
public static T Instance
{
get
{
if (instance != null)
return instance;
instance = FindObjectOfType<T>();
if (instance != null)
return instance;
GameObject resource = Resources.Load<GameObject>($"Singleton/{typeof(T).Name}");
instance = Instantiate(resource).GetComponent<T>();
DontDestroyOnLoad(instance.gameObject);
return instance;
}
}
}
what does this work for, and waht does it do
Read the page.
How far you hope to go if you cannot find simple answer yourself when they are literally setting in front of you.
I prefer having someone with experience explain it in a shorter way, than having to read a 3000 word page, beacuse after all, I code, not read
99% of coding is reading
How do you think most people learnt ?
through people with experience
The people with experience wrote that page.
Wrong. People with experience are few and they do not have time to teach everyone.
Instead, they leave books and post.
If you really want to have a typed experience, you can ask an LLM. You might be lucky and find some answer that are valid.
So, I've been using Unity events and looking at various videos on their application, but one thing confuses me. Most of the examples just directly set the subscriptions for the events in the editor. Managing all the even subscriptions between objects without having directly references doesn't seem to be covered clearly. I guess that just ends up becoming a "how to manage" the game in a way that makes sense without a mishmash of game managers with direct references to each other.
There's a lot you can just write your own if you wanted to, but UI button events are pretty convenient and I do use a lot of those.
unity events should only be used to hook local things like ui/some events in the same object that dont lead to massive callstacks
So it's reasonable for major systems to just use direct references instead?
systems should have a way to locate each other using at least some sort of service locator
GetComponent<T> is an example of one
they can also communicate through event bus
or have dependencies injected with the likes of zenject
haven't looked at an Evant bus, heard the term before
Zenject? is that a unity specific DI solution?
its extenject now
extenject is tailored for unity
service locator typically relies on a singleton doesn't it?
ahh so avoiding singletons at all costs may not be a good route