#archived-code-general
1 messages Ā· Page 279 of 1
show the new code
Nope as I said, its running up the the debug.log for highScore. Its definitely running
public void restartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
highScore = PlayerPrefs.GetInt("highScore");
Debug.Log(highScore);
Debug.Log("Checking if statements");
if (highScore > 0)
{
Debug.Log("High Score is below 0!");
highScoreText.text = "No Scores Currently";
}
Debug.Log("Checking the next if!");
if (highScore < 0)
{
Debug.Log("High Score is above 0!");
highScoreText.text = "High Score: " + highScore.ToString();
}
}```
Right, so it's not completely blank.
you wrote the logs backwards
you wrote below 0 when it's actually above 0
So highscore is never less than 0
so the if statements are working properly
It can never occur
hol up
Are you confused about what < and > mean?
highScore < 0 means high score is less than 0
and vice versa for highScore > 0, which means high score is greater than 0
That was def it. Sorry about that. These <> always get be befuddled. Greater than or less than were taught to be in the most gank way possible
Now I just gotta solve why its reverses to No Scores Currently afterward
Gotcha, much better than an alligators mouth
For programming behaviors in Unity ECS, do you create an author, a data container, and a system each time?
I suppose it's just separating the data from logic when compared to gameObjects if that's a correct way to think about it
On the other hand I was wondering if this means that compile time is longer since you have more scripts in general in comparison(This is just conjecture though)
#1062393052863414313 is probably the best place to ask
ah thanks
is it safe to load a memory dump (.dmp) file from an untrusted source (ie, random end user)?
Depends on what you mean by "load". If you mean opening it in an ide, then that should be safe. It doesn't actually run the code on your machine.
Besides, without the right symbol files, it's just a useless pile of binary data.
i mean I just wasn't sure if it was safe to load into an IDE, I've been surprised by some things recently like the unsafeness of stable diffusion .dat files (due to pickling) and similar things around certain binary serialization formats
It depends on how the data is loaded. But I've never heard any mention of dump files being dangerous.
I guess, it could be if you use untrusted symbol files, as then the data could be interpreted in an unwanted way.
well, its our debug symbols(pdb), so i'm not as worried about that, I just haven't looked at a dump file from a user before
Theoretically, any file from untrusted source can be dangerous. If they used some kind of vulnerability in your ide debugger, it's totally possible to plant a virus or run some other malicious code. Historically, there doesn't seem to be any reported cases of that happening, but you never know.
If that does happen to you, you can at least be proud as the first person that got hacked by a dump file.š¬
not a code question #archived-game-design
Is there a way for Custom Property Drawer to use internal class?
AnimCommand works only if its public
Is there a runtime error or a compiler error?
My guess considering it takes a Type it's hardcoded to check if the class is public, so I'm afraid it's not possible
IDE error, cant find it
But it doesnt make much sense since Unity shows internal class in editor
So if I dont have custom drawer it is shown in editor, but cant make custom drawer of internal class
That's not an error on the attribute but rather an accessibility error related to the project as a whole
AnimCommand appears to be in a different assembly, and making this internal restricts it to that assembly only
If you want it internal but also use it here, either move it to the same assembly or add this to the .csproj file of the project that has the class:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>Add the assembly name of the class that should use the class</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
Yep, two different assemblies
Yeah, iam not using assembly yet
my own assembly would fix it?
Well let me point out something else; if the class is in an assembly specific to the editor I am assuming that this assembly is not provided with builds as it's editor only
This would mean that you can no longer build because the code will not longer reference the class, causing an exception
So perhaps whatever you are trying to do should also be inside that editor assembly
You can test this issue by making it public again, verify the code compiles in the editor, and then building the project. It will fail with an error like "Unable to find AnimCommand class"
So the better thing to do here is finding an alternative which would allow you to do this, but abstracting the code that requires it into the editor assembly
Iam creating asset store item, and would like make public only things that matter. Else should be internal, like this class
I just created my own assembly definition and it works
one assembly is for the whole project
You could move the assembly and related code to the editor assembly and have it call the actuall class from there
But perhaps you should share more code and context
Would it be problem if I just put Drawer and runtime class into same project?
this works
The whole point is that you have an assembly that is not included in builds as it's specific to the editor
There are a million ways to go about this but a build assembly should not reference resources from an editor assembly
oh no, the class is in build assembly and editor assembly references class in build assembly
and those are default unity assemblies not mine
and i think ill just go with public, since i use one other library
I have a save system to save my player health and it's shield but the health isn't changed when I load, but the shield does, here's my code : https://hastebin.com/share/lojebeyote.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Log what the content you save actually saves as (the string saved into data.txt), and log what content[0] actually is
https://unity.huh.how/debugging/logging/how-to
My guess is one of these two is different than what you expect.
Maybe add a log for the shield value as well when you're loading
can you share the contents of data.txt
also you should use Path.Combine(Application.persistentDataPath, "data.txt")
if the health is 50 and the shield is 1, it's "50%VALUE%1"
#archived-code-general message
and log what
content[0]actually is
Did you actually check or is that an assumption?
it's the value that i saved
i checked
So that means that health.shield is actually set, considering it's the value you apparently expect
So the issue is not related to this code
You can additionally check health.Health but "1" should parse into a float just fine
screenshot the console
So it's not just shield..?
absolutely nothing wrong there so something else must be affecting Health
So what exactly makes you wonder why "shield" is not being loaded when it clearly loads?
Found the problem, it was just another float that made health to it's old value
thx everyone for helping me
Am I going crazy right now?
uint faceFlags = voxels[i].FaceFlags;
for (int j = 0; j < 6; j++) // <-- j is of type Int32, no?
uint flag = faceFlags & 1 << 1; // <-- second 1 is of type Int32, right?
// Everything makes sense, so no errors
Whereas...
uint faceFlags = voxels[i].FaceFlags;
for (int j = 0; j < 6; j++) // <-- j is of type Int32, of course.
uint flag = faceFlags & 1 << j; // <-- j is still of type Int32, yeah?
// Cannot implicitly convert type 'long' to 'uint'
Okay, I'll just cast it, then... But from where the hell does long appear?
Dunno, maybe a question for !cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Are you sure that's the correct line?
Also happens for me š¤·āāļø
most odd, 1 and j are both int
Right? Doesn't make sense to me
Only noticeable difference is that j is an int and 1 is perceived as Int32 but that doesn't explain anything
default type for numeric integers is int32
Take a screenshot of what it looks like in the ide
That would explain why I need an explicit cast, but why from type long?
Is compiler just goofing?
not that it makes sense but the cast to Int64 would preserve the sign during the bit shift
-1 for example would require an upcast to Int64 to preserve all bits
It does seem like any bitwise operation between int and uint causes the error
yep, C# will not automatically allow you do to something which may lose data
1 << 1 is a compile time operation. 1 << j is runtime
how to create database Update .csv file, when a simple task done! and saved in .csv file
I don't think using excel files as a database is a good idea
how to assign prefab child object to a different prefab object's script?
they must both be part of another prefab together
if these objects are completely independent prefabs
so what the best idea
please I want to collect some data from Player and put it in .csv after finishing the game
When it comes to games you would encrypt the data and write the bytes to a text files
But you can also just use regular text files and serialize the data as JSON into it, using Newtonsoft
JSON is generally the best format for sharing data but it won't be secure.
Then again, neither will .csv files.
I don't mind about secure to be honest its just fake data and it will keep change not stored
thank you sooo much FusedQyou
by the way I won't face a problem when build apk? @thin aurora
I have no idea how mobile works but Unity has a persistent data constant you can use as a place to save data
I would guess it works there too
As to what you actually save, I don't see why that would matter. I don't think there are restrictions
Note PlayerPrefs is also a feature you can use for saving so if you want simple saving you can also use that.
Is there a way to turn an existing Prefab (that already is the parent to multiple Prefab Variants) into a variant of another Prefab? I just decided to make a more abstract prefab - but I find no way to make the existing root prefab a variant of that newly created Prefab
transform.hasChanged is always true, right? It's not managed by Unity in any way. It's basically a flag that was put there for me tu manually set and unset, right?
Has the transform changed since the last time the flag was set to 'false'?
A change to the transform can be anything that can cause its matrix to be recalculated: any adjustment to its position, rotation or scale. Note that operations which can change the transform will not actually check if the old and new value are different before setting this flag. So setting, for instance, transform.position will always set hasChanged on the transform, regardless of there being any actual change.
Unity does change it. It sets it to true whenever a change to the transform is made. It will, however, never set it to false. That's what you need to do, set it to false, and then you can periodically check if it has been set to true to know if the transform has been changed since you last set the flag to false.
Ok, thank you, that's the context that's missing from numerous threads on forums and in google
I wonder though, what's the best way to set it to false
because it can happen that multiple things could try to update certain things at different times
What problem are you trying to solve with this flag?
Set it simply at the end of FixedUpdate, or something?
I have a component that sets a shader uniform, and I see that it's called passively all the time, so I need to limit the number of times it's called to only happen when it really changes
And this shader uniform is directly related to the transform of an object?
yes
If I pass random numbers to Resources.InstanceIDToObjectList shouldn't it return null to them (they are invalid ids after all)? I noticed that it seems to crash.
Am I supposed to first call Resources.InstanceIdsToValidArray, and with the ones that returns true pass them to Resources.InstanceIDToObjectList?
It's exactly:
var spaceTransform = Matrix4x4.Rotate(Quaternion.Inverse(transform.rotation));
spaceTransform *= Matrix4x4.Translate(-transform.position);
It's later used in raymarching (in shader)
You should set it to false at the same time you've detected that it has been set to true and you've updated the shader uniform.
That way, you'll know if it has changed since you last updated the shader uniform.
If you set it in FixedUpdate, then you'll only know if it has changed since the last FixedUpdate.
Good morning, I'm finishing my first game. But I'm stuck on something that should be simple but I don't know how to do it. my boss summons these demons. However, if you die and try to press restart the game crashes, from what I think, it's because the demons are trying to follow the player, but the player is dead and has nothing to follow. How do I not have any more summons when the player dies? I will send the link to the codes below. demon controle; https://paste.ofcode.org/Wf8QGE6PrVX5AFQNX9ufNP player; https://paste.ofcode.org/RDJn7EBygswTGacKTiaxgQ boss; https://paste.ofcode.org/r5fYms2KqPpKb3KdNSqpfz
a very crude method would be to check if the player is null and if so, return out of the while loop.. a probably better way would be to have an event that you can register on, i.e. UnityAction OnDeath on the player, for example
I understood. thanks
Hello, I am having a problem. When I put the enemies into the scene one by one, the player takes damage as I expected. However, if I put two enemies at the same time, the player doesn't take damage as I expected. It just takes damage from only one enemy's power
Bug is in code
thanks a lot i will try to solve
There's absolutely no reason each enemy needs its own numbered script
They should both use the same script
Also the two you have are different
i see, i will try that way thank you @leaden ice
I have the following situation:
Obj1 at scene root
Obj2 at scene root
I have Obj1 local position and Obj2 local position. I wanna make Obj2 move towards Obj1.
In this case, the local position is equivalent to the world position, since they're in the scene root.
But in case they weren't, I tried converting Obj1 local position to world position with TransformPoint and then later convert it to Obj2 local position by InverseTransformPoint. But this isn't working. Why is that?
Every transform has .position which is the world space position
Yeah, I'm aware of that, I'm trying to understand why they didn't end up in the same coordinates
You'd have to show your code
your explanation was vague
but basically:
x.TransformPoint(somePosition) expects that somePosition is expressed as a local space position in the coordinate space of the object x
if it wasn't expressed that way, it won't have worked
for example some other object y has y.localPosition which is not expressed in local space of x unless y is a child of x
if y is a child of some other object then its local position is expressed as a coordinate in the space of that parent
local position is always in the coordinate system of an object's parent.
public void OnUpdate(ref SystemState state)
{
float deltaTime = SystemAPI.Time.DeltaTime;
float3? playerPosition = null;
foreach (var (transform, _) in SystemAPI.Query<RefRO<LocalTransform>, RefRO<PlayerTag>>())
playerPosition = transform.ValueRO.TransformPoint(transform.ValueRO.Position);
new EnemyMovementJob
{
DeltaTime = deltaTime,
PlayerWorldPosition = playerPosition
}.Schedule();
}
[BurstCompile]
public partial struct EnemyMovementJob : IJobEntity
{
public float DeltaTime;
public float3? PlayerWorldPosition;
[BurstCompile]
void Execute(
ref LocalTransform transform,
in EnemyMovement enemyMovement
)
{
if (PlayerWorldPosition == null)
return;
float3 currentPosition = transform.Position;
float3 targetPosition = transform.InverseTransformPoint(PlayerWorldPosition.Value);
float3 newPosition = MathUtils.MoveTowards(
currentPosition,
targetPosition,
enemyMovement.MoveSpeed * DeltaTime
);
if (math.distancesq(newPosition, targetPosition) < .1f)
return;
transform.Position = newPosition;
}
}
This is the code
I'm basically trying to make it hierarchy agnostic
If I simply skip the Transform/InverseTransform, it all works well because they're in the scene root
just use world space position
you're overcomoplicating it
The point is understanding it, I don't get why it isn't giving me the same results 
debug each operation and compare
mm, am not seeing where you're using localPosition in this, buuut any chance that you're using TransformPoint with the local position of the same transform? like transform.TransformPoint(transform.localPosition)... that would be incorrect
if you're doing unnecessary operations and getting undesired results then I assume it's doing some extra matrix operations without caring what space it currently is in
I'm not sure your player world position makes sense
transform.ValueRO.TransformPoint(transform.ValueRO.Position)```
this in particular seems a little like nonsense to me
oh yeah wat
I think you should just switch to LocalToWorld instead of LocalTransform all over this code
I'm inexperienced in DOTS/ECS
but whatever you need to just get world space positions
Yeah, that seems to be the issue
can always grab the matrix4x4 from the transform and do the calculations yourself if you want to make actual sense oh, you just care for a point which you can probably just work out with differences
generally Position is your position in your parent's coordinate space but TransformPoint transforms a point in your own coordinate space to world space. So the input coordinate space here doesn't match the expected input coordinate space
because you're trying to reference non static fields from a field initializer
line1 etc... are all non static fields
Even if you do serialize them, you still need to follow the rules of c#
everything on the right of the = sign is a field initializer
if it's a mono, do it in start, otherwise use a constructor
Also you should rewrite the code to simplify:
public string[] lines;
public string str;
void Awake(){
str = string.Join("\n", lines);
}```
Anytime you have "numbered" variables you are better off using an array or a list
I'm having trouble spawning items in a specific room. When i do, the collision physics of the cube I'm using as my room act on the object and force them out
Wrong channel I think, though I was in beginner
probably want to split layers for items and player for physics
How would I go about making sure an animation speeds up to match exactly a certain distance a GameObject has to travel?
A card can be played anywhere on the board. I want to play a little animation that nicely places the card, and I'm using MoveTowards to move the card to the board position. However, of course cards in the middle of the board are reached much quicker than those at the edge of the board. I guess what I'm trying to ask is how to go about animating objects without a fixed animation duration
need to normalize the distance by a time
Yes, but I want the other way around :D Changing the animation speed so to speak
like, are you asking how to do it with the animator? The math should just be like
animationDuration = distance / speed
Mm, let me record a gif of what I mean
been a while since ive done some of this stuff but usually I remember it being pretty simple with adjusting the clips
there's some stuff there
So this example shows it quite well: The card moves from the hand to the board, but notice how the placement animation is much faster when placed on the lower row because the card does not have to travel that far
right, you'd do a mixture of movetowards and change the animation speed playback
could also just play the animation when the card lands too
But wouldn't I need to know the time it takes to reach the destination to change the speed?
well, you set a base duration of say 2 seconds
so it would be distance / duration animation duration / distance (one or the other lol)
which would be your animation playback speed per second*
or like I said, just play a normal animation when the card lands, and instead of adding an animation when moving you'd just move it with some parameters
Oh so calculate Vector2.Distance between the hand card and its target position and tinker with the divisor to find a nice playback speed? I think that could work!
Thanks for the help :)
public class ExampleScript : MonoBehaviour
{
public Animation animation;
public void PlayCardAnimation(float distance)
{
//normalizedSpeed = (animation.length / distance) / animation.length;
//Ah, animation.speed is a multiplier so it may be this one instead. Try both.
//Can also add a speed multiplier to distance
normalizedSpeed = animation.length / distance;
animation["PlayCard"].speed = normalizedSpeed;
animation.Play("PlayCard");
}
}```
probably look more into changing the speed because the api says it's done with states but I assume you can just change it for the clip alone? Not sure
maybe you have to edit the keyframes/curve if you did it by clip
If I have a class ConsumableItem that inherits from ItemInventory, can I use ConsumableItem in an ItemInventory variable?
yes. Inheritance denotes an "Is A" relationship.
I.E. if ConsumableItem : ItemInventory then ConsumableItem IS AN ItemInventory
Ok thanks! I tried that in VS and throw me an error, maybe it's a problem only for VS
You should show what the error is. An error is an error
you would have to show the code you tried and the error you got
It's important to read your error messages and try to understand them
It was Cannot convert from ConsumableItem to ItemInventory
Then ConsumableItem did not inherit from ItemInventory as you said
again, show the code you tried.
including the definitions of those types and where you tried to use them
It's fine, I scrapped it because it didn't work. I was just asking for confirmation
it will work if you do it properly
You probably made a simple error. Conceptually what you asked for works fine.
https://www.w3schools.com/cs/cs_inheritance.php
A decent resource on it where you can modify and run the code. Also there is more information related if you go the next page
Hey guys I have an issue, it's the first time that I'm suing the new unity input system and I'm starting to find some issues.
One of the being that the character is really slippery so it's really hard to move since I'm creating a platformer.
Here is my code:
{
rb.velocity = new Vector2(1 * moveSpeed * speedMultiplier * 0.8f, rb.velocity.y * jumpForce/1.5f);
}
if (moveDir.x < -0.1f)
{
rb.velocity = new Vector2(-1 * moveSpeed * speedMultiplier * 0.8f, rb.velocity.y * jumpForce/1.5f);
}
if (moveDir.x == 0)
{
rb.velocity = new Vector2(0 * moveSpeed * speedMultiplier, rb.velocity.y);
}```
Like this everything works fine, but the issue is the last if statement, where it's written "if moveDir.x == 0" because by doing this I can't apply any force to the game object other than just walking.
The issue is that if I remove that part the player becomes slippery and I don't know how to fix this
My idea was using something similar to "GetAxisRaw" that I remember used to do the same thing that I need but for the new input system
this is going to sound really dumb⦠but letās say I have a Stack, and want to potentially remove an entry⦠that might be in the middle of the stack.
Is there any way to do this without essentially doing ToList() and remaking the whole thing?
it sounds like you don't want to use a stack š
honestly, this is why stack and queue suck
i have for 5 months now. Until right now
Times Change
they're great in theory but sooner or later you just want a list
itās for a draw history, so I can Undo/redo. And I want to check that the current entry isnāt effectively just doing nothing.
but yeah, the point of these structures is the restrictions they enforce, so if those restrictions are getting in the way I say to just use a different one
actually⦠maybe I donāt need to do that at all. the stack lives on!
hah, and sometimes those restrictions help you to save time by forcing you to think things through! nice
in my case, they really should be a stack
iām trying to check if the commands in my stack (corresponding to one press of an Undo button) is equivalent do doing nothing
it would probably be much easier to just only insert real operations? maybe you end up with the same problems though
pretty interesting question...you could sim the state forward or you could implement a way for each command to check if it will be a no-op, but both of those sound like a lot of work to me
itās just a bit messy because of how my level editor works
undo/redo can be implemented by two stacks
stack a:1 2 3 4 5 6 7 8
stakc b:(empty)
```eg if you undo to 3, pop 8 7 6 5 4 from stack a and push to stack b
```cs
stack a:1 2 3
stack b:8 7 6 5 4
```with some checking (if some elements are null eg 4, 7)
```cs
stack a:1 2 3
stack b:8 6 5
```for redo, just pop stack b and push back to stack a
if one new operations is done eg 9, then clear stack b
```cs
stack a:1 2 3 9
stack b: (empty)
```but i will just keeping one list and two pointers and only push non null operation
when you write X, it deletes what is there, logs the deletion, writes X, then logs the addition
i have undo/redo working with two stacks exactly how you describe
but a single undo/redo entry is also expressed as a stack of changes
find out if the operation can cancel out each other is not good idea.....
i mean like:
ābackspace to delete A, then type Aā
as one entry should be nothing. So even if you click and do that, you should not need to click undo one time to do nothing
yeah, i think you would want to batch those together into one undo
then every 'undo' press should do something, right?
correct
i guess i'm trying to imagine a situation where this matters
like what sort of thing is the user doing where they'd end up with an 'empty' undo in the stack? i agree that trying to collapse together actions which cancel each other out is a bit much
but maybe i'm misunderstanding
imagine you are in paint, and drawing to the canvas. You now draw a red pixel onto a red pixel
the Undo stack should not be changed
i see what you're saying but i don't think it matters at all
or at least I do not want it to be changed
like the lift to solve this is just not worth it for what you gain
i donāt like it, it makes me unhappy, so I want it to be different
then i think you gotta do one of these two things
you can check if the operation is exactly the same as (all the states) stack top
ah yeah that's true
you also could maybe do this at a higher level, e.g. do some validation before the actions are dispatched to ensure they aren't no-ops
but i think this is not friendly to command pattern,
you have is operator btw
my current solution:
/// <summary>Check if the most recent growing entry has just the given TilePlacementInstance
/// on the top. If it does, remove it and return true. Else return false.</summary>
public bool TryUnlogLastTile(TilePlacementInstance instance) {
if (!loggingNewEvent && !loggingRedoEvent) return false;
if (currentGrowingEntry.placements.TryPeek(out TilePlacementInstance recentTile)
&& recentTile == instance) {
currentGrowingEntry.placements.Pop();
return true;
}
return false;
}```
Invoke this right before writing a tile has been added to the canvas
so that if i try to paint a red pixel red, nothing happens
It would look like:
red pixel
delete red pixel, log old pixel was red
write red pixel
tryunlogRedPixel
If it was previously the same red pixel, done
If not, log the new red pixel
(also that's a struct btw)
Then it is easy when logging a new undo entry to abort if the stack count is 0
It won't catch times where the undo entry has a bunch of crap in it, but it only matters to block if the stack for the one undo press is only the one tile.
ty for helping me think through it
Clover 0.5.0 released!
Clover is vscode extension for unity.
You can check your prefab, scen file in vscode now!
Search vscode marketplace clover by Elik Song.
Also if you have a interesting contribute, https://github.com/novemberi/clover
#1180170818983051344 or #1080140002849214464 is the appropriate place for this
Either way according to #šācode-of-conduct advertising isn't allowed
except in those channels
I understood. Thank you. I'll move to dev-logs
Do I have a way of knowing what vertices unity duplicated during the mesh import process other than a distance check?
define duplicated
talking like ones that were duplicated because of uv splits and normal splits
well verts in the same location with different normals
or just verts in the same location as eachother
whats the reason for needing to know? might be a other way to approach the problem
In the process of writing a solver based on positions based dynamics. A part of the solving process is to project distance constraints.
I am trying to sample a mesh and generate the distance constraints based on the mesh's vertices, but I'm realizing now that it won't be that straightforward.
Current plan is to sample all verts for "duplication", generate a list of unique vertices. Bind all the duplicates to their unique counterpart and operate on the unique verts. Then I can just iterate on the bound indices for the skinning process.
It's kind of an ugly layer to strap on top
Did you try tween library?
is this the same as maxUse -= 1 ?
i just found this randomly
i wish i found this sooner
so guys
im making a rhythm game
but im stuck on how to make a system where the notes go down and you can hit them
yes
ty
Correct, and there are lots of other operators, worth reading up on. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#decrement-operator---
crazy how useful knowing the absolute basics of the language is. who would have thought
sorry man i started csharp and unity only 4 months ago
i dont see how hitting on me for this small thing is helping
has anyone implemented marching cubes and can give me a hand>
I think we even have LeanTween on the project. Why? ^^
Thank you! I will definitely try it in a bit
I usually animate those things through tweens and DOTween has tweens based on duration or speed
Mmm I see. I've not really used them, yet, but it might be worth a shot!
Hello. How to I properly declade a NetworkList<int>? I want it to be initiated with numbers from 1 to 12.
Hi, I don't want you to see my character while others see it. I did it a bit by myself and a bit from a guide and I got an errors: ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gamemeneger : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (gracz == gracz.mojgracz)
{
gracz.gameObject.transform.Find("Man_Full").gameObject.SetActive(false);
}
else
{
gracz.gameObject.transform.Find("Man_Full").GetComponent<Renderer>();
}
if (gracz.team == Team.BLUE)
{
gracz.gameObject.transform.Find("Man_Full/Man_Half_Body_Mesh").GetComponent<MeshRenderer>().material.color = Color.blue;
}
else
{
gracz.gameObject.transform.Find("Man_Full/Man_Half_Body_Mesh").GetComponent<MeshRenderer>().material.color = Color.red;
}
}
public void SpawnGracza()
{
GameObject mojgracz = PhotonNetwork.Instantiate("Gracz", new Vector3(58.29f, 0f, -837.0149f), Quaternion.identity, 0);
mojgracz.GetComponent<FirstPersonMovement>().enabled = true;
mojgracz.GetComponent<Jump>().enabled = true;
mojgracz.GetComponent<Crouch>().enabled = true;
mojgracz.transform.Find("First Person Camera").gameObject.SetActive(true);
}
}
and secound script: ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gracz : MonoBehaviour
{
public static gracz mojgracz;
public string nick = "";
public PhotonPlayer pp;
public Team team;
public static List<gracz> gracze = new List<gracz>();
public static void debugujliste()
{
string dbgS = "debugujliste" + gracze.Count;
int i = 0;
foreach (var gracz in gracze)
{
dbgS += "id:" + i+ "nick:" + gracz.nick + "team:" + gracz.team;
i++;
}
Debug.Log(dbgS);
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.L))
{
debugujliste();
}
}
public static gracz ZnajdzGracza(PhotonPlayer pp)
{
for(int i =0; i < gracze.Count; i++)
{
if (gracze[i].pp == pp)
return gracze[i];
}
return null;
}
}
public enum Team { RED, BLUE}```
If someone helps me, I will love him
ā¤ļø
Hey I'm having a strange issue where the OnSceneLoaded event is calling 4 times each time 1 scene is loaded?
Did you disable domain reload?
If so, you need to make sure you're unsubscribing from static events
also, you might just be subscribing repeatedly
hmm, well, the subscription would be this line right?
SceneManager.sceneLoaded += OnSceneLoaded;
that's in the Start() function of a Singleton, so I don't think that case.
as for the disable domain reload, I don't think I did... but i'll look into that thanks
is that the problem that I don't have it enabled?
ah. yes, the singleton does get recreated if I reset my game (it's a roguelike)
so that would make sense
i'll make sure to do that, thx
yep that fixed it! woohoo
Can somebody please refresh me rq on how to use the "new" input system? The way I did it before was using the InputActionAsset I made to assign InputAction components, but currently I am at a blank on how to do button detection. Something like this? ```cs
private void OnEnable()
{
jump = controls.Player.Jump;
jump.Enable();
}
private void OnDisable()
{
jump.Disable();
}
public void Jump(InputAction.CallbackContext Context)
{
if (Context.performed || IsGrounded())
{
return;
}
}```
You'd have to either subscribe to the performed event on your action or poll it in Update
As it is right now your Jump() function is not being used by anything
for a jump i normally just sub to its onPerformed
What are some ways I can do the first one?
jump.performed += Jump;
where Jump is a method accepting the arg InputAction.CallbackContext
sub and unsub from it in OnEnable and OnDisable
then when ever jump is pressed your Jump method gets called
so like this? ```cs
private void OnEnable()
{
jump = controls.Player.Jump;
jump.performed += Jump;
}
private void OnDisable()
{
jump.performed -= Jump;
}```
yup, though you will still want to call Enable
like your previous one
though if you are binding to multiple controls, you could enable the whole action group instead of just the one action
Do I enable before checking performed, and disable after unsubbing?
Alright cool, thanks :D
this is how i handle things that are just button pressed i want to call a function on
for other things i just poll for it in update
like this. but you need to actually link the delegate in your playerinput component
and the method needs to be a function of InputAction.CallbackContext
Like this? ```cs
private void OnEnable()
{
move = controls.Player.Move;
move.Enable();
jump = controls.Player.Jump;
jump.Enable();
jump.performed += Jump;
}
private void OnDisable()
{
move.Disable();
jump.Disable();
jump.performed -= Jump;
}
public void Jump(InputAction.CallbackContext Context)
{
if (Context.performed || IsGrounded())
{
}
}```
fun fact, if you just subscribe and unsubscribe in Awake/Start and OnDestroy you only have to enable and disable the actions in OnEnable/OnDisable
discord formating is being dumb rn
private void OnEnable() {
playerInput.Gameplay.MousePosition.performed += OnMouseMove;
playerInput.Gameplay.MouseLeftClick.started += OnLeftClick;
playerInput.Gameplay.MouseLeftClick.performed += OnLeftClick;
playerInput.Gameplay.MouseLeftClick.canceled += OnLeftClick;
playerInput.Gameplay.MouseRightClick.performed += DirectRotateButton;
playerInput.Gameplay.Reject.performed += OnPressReject;
drawTypeButton.OnBuildModeChange += ForceReleaseDraw;
}
private void OnDisable() {
playerInput.Gameplay.MousePosition.performed -= OnMouseMove;
playerInput.Gameplay.MouseLeftClick.started -= OnLeftClick;
playerInput.Gameplay.MouseLeftClick.performed -= OnLeftClick;```
This is what mine looks like
this is a silly question but... tilemaprenderers can be referenced, right? I need them to be
yes, configure your !IDE then use the quick actions to import the correct namespace
https://docs.unity3d.com/ScriptReference/Tilemaps.TilemapRenderer.html
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
will the |= operator call the right hand if the left hand is already true?
Like is it equal to
bool myBool = SomeValue();
myBool = myBool || SomethingElse();
where if myBool is true it doesn't call SomethingElse()
The | operator always evaluates both operands
You are probably looking for ||= not |=.
that's not a thing
Huh.
there is no ||= operator
Not sure why it's not a thing.
I agree it should be a thing, but I am just doing the second way I said now.
Oh god please no. I want to be able to have readable code bases
It's pretty trivial to test it, but it seems like |= does not short circuit.
You mean for things like if a button is being held down?
I feel like being able to short circuit is a good enough reason to have ||= and &&= added to the language.
I thought all the operators could be written like that too
|| and && are short circuiting
But ||= and &&= do not exist.
Yes. I'm struggling to find an actual use case though
I mean, lots of languages have it, and the original question asks for it (presumably wanting short circuit)
I dont see a use case for &&= but I do see how ||= could be used
if (this = 19 ||= 20) {)
but then again it is kinda not necessary
Oh god
Please no
I think it's better to write your code in a way that makes it easy to read, rather than quick to write
By that logic we shouldn't have any compound assignment at all.
No, compound assignments for integers are not used in expressions
||= and &&= would be used in expressions
Hell no
||= and &&= is no less useful than +=, -=, or ??=.
That's a very questionable take, ??= is very much used everywhere in C#, compound assignment is not limited to arithmetic operators.
Many other languages also have ||= and &&=, not sure what more evidence you need that they have their utilities.
I'm not saying other languages don't have them. I'm saying hell no to C# having them.
The thing is that they are used on bools, which themselves are expressions.
i use | | and && all the time lol
But who am I to gate keep š¤·āāļø
If you like it you like it ^^
It's about a potential compound assignment version of them
Doesn't seem like GitHub code search allows back reference regex groups, so I can't do a search on foo = foo || ... pattern.
But just searching /[a-zA-z0-9]+ = [a-zA-z0-9]+ \|\|/ (which matches foo = bar || ...) and even the first page of dotnet/runtime repo is full of examples that could be simplified with ||=.
hey quick question how to do you random.Range a set value again
wait never mind i got it ahha
to the person asking for random value and deleted the message:
You could set float min and max for the numbers, then you could Random random = new Random(); and then you could generate the number with randomValue = random.Next(minValue, maxValue);
minValue and maxValue are the float numbers*
yea thx dude i was just like having a brain fart haha
can also just use unitys random instead
np
Random.Range(min, max)
or that, but this came quicker to mind lol
i was just a bit confused why i couldnt set the value in the begining
Is this a good way of detecting sprinting input? Sprint being a bind of an analog value action: isSprinting = controls.Player.Sprint.ReadValue<float>() > 0;
if you are talking about the System.Random one, its because it lets you creates multiple instances of random so you can seed them differnetly. can just make the instance once and keep reusing it
Sprint being a bind of an analog value action
is there a specific reason for that instead of just making it a Button action?
No
well, I personally just make my sprint action a Button and subscribe to the performed and canceled events. then you don't need to poll the value constantly
That works much better, thank you!!
Hey there => I'm using netcode for game object. I add children to a prefab with a network object at runtime, then spawn that prefab but the Children are not spawned on clients. Is it something I'm not supposed to be able to do because the template gameObject original prefab doesn't have these children in it ?
how do I use IJsonMigration? The example that is given doesn't make a whole lot of sense to me. Should I be implementing this on a class that is saved? I can't imagine it's magically called when versions don't align. Or am I suppose to call its method if it fails to serialize?
I'm using BlueUnity plugin to read data from Arduino Uno HC-05. This BlueUnity plugin basically calls a Java class and will return a string containing JSON formmated text. This is the example provided by BlueUnity plugin to read data.
public class BluetoothService
{
private static AndroidJavaClass unityPlayer;
private static AndroidJavaObject activity;
private static AndroidJavaObject context;
private static AndroidJavaClass unity3dbluetoothplugin;
private static AndroidJavaObject BluetoothConnector;
// creating an instance of the bluetooth class from the plugin
public static void CreateBluetoothObject()
{
if (Application.platform == RuntimePlatform.Android)
{
unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
context = activity.Call<AndroidJavaObject>("getApplicationContext");
unity3dbluetoothplugin = new AndroidJavaClass("com.example.unity3dbluetoothplugin.BluetoothConnector");
BluetoothConnector = unity3dbluetoothplugin.CallStatic<AndroidJavaObject>("getInstance");
}
}
public static string ReadFromBluetooth()
{
if (Application.platform == RuntimePlatform.Android)
{
return BluetoothConnector.Call<string>("ReadData");
}
return "";
}
}
the problem is that when I try to call BluetoothService.ReadFromBluetooth from another script's Update function, the game stutters when the string is empty.
It freezes for 80ms (ReadFromBluetooth takes 80% of the duration) when the string is empty (not null). How to avoid this?
For additional context: It's stuck for around 50ms on the line "return BluetoothConnector.Call<string>();" in the profiling.
I mean it kinda sounds like you're doing some IO on the main thread
likely you'd want to process the bluetooth stuff on a background thread
well, it calls custom Java script though
yes, I tried that as well
private static Queue<string> messageQueue = new Queue<string>();
public static void ReadDataInBackground()
{
while (true)
{
string data = BluetoothConnector.Call<string>("ReadData");
// if (data.Length > 1)
// {
lock (messageQueue)
{
messageQueue.Enqueue((data == null).ToString());
}
// Adjust delay based on your needs (e.g., 0.1f for 100ms)
Thread.Sleep(1);
}
}
public static string GetNextMessage()
{
lock (messageQueue)
{
if (messageQueue.Count > 0)
{
return messageQueue.Dequeue();
}
else
{
return "";
}
}
}
and when I try to run GetNextMessage in another script's Update, it returns as True meaning that the "string data" is null
when I try this function instead, the returned string is not empty/null. But it stutters the game
Oh, one more thing, the bluetooth device sends data every 100ms to the connected device.
GetNextMessage returns a string not a bool
messageQueue.Enqueue((data == null).ToString());
that was debugging whether the data is null or not
oh - you can just use ConcurrentQueue btw instead of manually locking
oh, wait let me see
hold a minute while i'm trying that concurrentqueue
anyway it's not going to change anything really
sounds like your Java function is returning null
and by the way
Thread.Sleep(1)
that waits for a single millisecond
you probably want to wait a lot longer than that, around 100ms based on what you said
And it's unclear exactly what this ReadData function does
weird, but the previous function return a filled string instead
public static string ReadFromBluetooth()
{
if (Application.platform == RuntimePlatform.Android)
{
return BluetoothConnector.Call<string>("ReadData");
}
return "";
}
it gives the string back
void Update()
{
if (IsConnected)
{
try
{
string datain = BluetoothService.ReadFromBluetooth();
if (datain.Length > 1)
{
dataRecived = datain;
print(dataRecived);
}
}
catch
{
BluetoothService.Toast("Error in connection");
}
}
}
yes
basically this
when using queue I tried this
void Update()
{
if (IsConnected)
{
try
{
string datain = BluetoothService.GetNextMessage();
if (datain.Length > 1)
{
dataRecived = datain;
print(dataRecived);
}
}
catch
{
BluetoothService.Toast("Error in connection");
}
}
}
let me try to open the java class, i'm glad that the developer made the source open
ok so when I open the java class, the function is like this
public String ReadData(){
try {
if(inputStream.available() > 0){
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
return reader.readLine();
}
else return "";
} catch (IOException e) {
return "";
}
}
this is the java code
based on your suggestion, I tried doing this
private static ConcurrentQueue<string> messageQueue = new ConcurrentQueue<string>();
public static void ReadDataInBackground()
{
while (true)
{
string data = BluetoothConnector.Call<string>("ReadData");
// if (data.Length > 1)
// {
// lock (messageQueue)
// {
messageQueue.Enqueue((data == null).ToString());
// }
// Adjust delay based on your needs (e.g., 0.1f for 100ms)
Thread.Sleep(75);
}
}
How are you calling the ReadDataInBackground?
ok so honestly given the way the java is written
I would delete the Thread.sleep entirely
er wait maybe not
honestly wonder if it would be better to delete that if statement in the Java code and just have it block indefinitely
then you wouldn't need the sleep
public class BluetoothConnection : MonoBehaviour
{
public void StartBluetooth()
{
if (SimulateData) { isConnected = true; return; }
if (!isConnected)
{
// isConnected = BluetoothService.StartBluetoothConnection(deviceName.text.ToString());
isConnected = BluetoothService.StartBluetoothConnection("HC-05");
// BluetoothService.Toast($"{isConnected}{!SimulateData}");
// BluetoothService.Toast("HC-05" + " status: " + isConnected);
// StartCoroutine(CReadBluetooth());
thread = new Thread(() => BluetoothService.ReadDataInBackground());
thread.Start();
}
}
}
the StartBluetooth will be called on button's OnClick
oh sorry in the java?
public String ReadData(){
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
return reader.readLine();
}
Yeah I was saying like
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
return reader.readLine();
} catch (IOException e) {
return "";
}```
because that should just block until there is a line of data
as long as it needs to wait
otherwise the way you had it, it's going to return an empty string immediately when there's no data in the stream
but shouldn't it return an empty string, not a null value?
actually I don't see any circumstance in which this code should return null
SO that's weird for sure
this part stutters ONLY when the string is filled with characters
maybe some weirdness with how Unity handles plugins and multithreading
when the string is empty but not null, it runs smoothly, I saw it in the profiler that it only stutters when it has characters in the string
i personally don't care if the java takes a shitton of time to read data, what matters is that the game freezes when waiting for incoming data
Have you profiled again to see what's causing the stutter with the changes Praetor gave you?
Now that the data reading in on a different thread it shouldn't block main thread anymore.
no, it doesn't stutter, but the data is null instead
which is not what I want
Ah.
Right because that's when it's actually reading data
public static void ReadDataInBackground()
{
while (true)
{
string data = BluetoothConnector.Call<string>("ReadData");
if (data != null)
{
messageQueue.Enqueue((data).ToString());
Thread.Sleep(75);
}
}
}
I even tried this just for the piss but it gives me nothing instead, (well, the conclusion is that the data is always null)
any advice on this? For reference: https://docs.unity3d.com/Packages/com.unity.serialization@3.0/manual/index.html (scroll down to where it says migration)
hi, may anybody tell me why in my chess game this script summons a queen after promotion correctly (1) but when i tried to change it with giving few options to the players it suddenly stopped working (2) The piece is always black and it spawns always on 1 side of the map, not where the pawn was?
https://gdl.space/acizifomok.cs working one
only with queen promotion
https://gdl.space/aziyeqotaq.cs not working one
with all 4 promotions
here i put the codes
without debug.log
{
TakePiece(piece);
Queen.SetActive(true);
Bishop.SetActive(true);
Knight.SetActive(true);
Rook.SetActive(true);
Debug.Log(piece.occupiedSquare);
Debug.Log(piece.team);
if (QueenPromote)
{
chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Queen));
QueenPromote = false;
Bishop.SetActive(false);
Queen.SetActive(false);
Rook.SetActive(false);
Knight.SetActive(false);
}
else if (RookPromote)
{
chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Rook));
RookPromote = false;
Bishop.SetActive(false);
Queen.SetActive(false);
Rook.SetActive(false);
Knight.SetActive(false);
}
else if (BishopPromote)
{
chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Bishop));
BishopPromote = false;
Bishop.SetActive(false);
Queen.SetActive(false);
Rook.SetActive(false);
Knight.SetActive(false);
}
else if (KnightPromote)
{
chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Knight));
KnightPromote = false;
Bishop.SetActive(false);
Queen.SetActive(false);
Rook.SetActive(false);
Knight.SetActive(false);
}
Debug.Log(piece.occupiedSquare);
Debug.Log(piece.team);
}```
i have this function currently
Queen, bishop, knight and rook at start are buttons
this code doesnt work, it doesnt read the position
as we can see it loses the values mid code
any idea what had happened?
quick question - is Piece a monobehaviour?
if so - don't do this:
if (piece)
(we don't do that here meme)
It doesn't work like you might expect it to, since operator== is overloaded and means something different in unity (it means if it's null or has been destroyed this frame - which might be fine for your use case but .. you probably ought to not do that anyway since it's a weird construct)
private void TakePiece(Piece piece)
{
if (piece)
{
grid[piece.occupiedSquare.x, piece.occupiedSquare.y] = null;
chessController.OnPieceRemoved(piece);
Destroy(piece.gameObject);
}
}
public void PromotePiece(Piece piece)
{
TakePiece(piece);
chessController.CreatePieceAndInitialize(piece.occupiedSquare, piece.team, typeof(Queen));
}
Also....... you're calling TakePiece in promote piece (first), then trying to access piece.occupiedSquare - it'll work because Destroy(piece.gameObject) doesn't actually kill it until the end of frame, but .. you should protect yourself against bugs like this by getting the square the piece is on first then destroying it and creating a new one
@signal moon Your PromotePiece and Promote__ methods are a mess - don't do this sort of wonky "loose" coupling where one hand sets a flag and expects the other hand to read the flag. Instead - just call promotepiece directly from promote__:
internal enum PromotionType { Queen, Rook, Bishop, Knight, }
public void PromoteQueen(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Queen);
public void PromoteRook(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Rook);
// .. etc
private void PromotePiece(Piece selectedPiece, PromotionType promotionType)
{
// remember to grab the square, team first
Vector2Int coords = selectedPiece.occupiedSquare;
TeamType team = selectedPiece.team;
TakePiece(selectedPiece);
chessController.CreatePiece(coords, team, promotionType);
}
i just finished tutorial about this, as far as i know piece stores values about current piece, and somehow not just one, im returning to unity and i havent heard of something like that, but it seems it is possible
i mean.. look at your piece class and see if it inherits from monobehaviour
is it
public class Piece {}
// or
public class Piece : MonoBehaviour {}
if it's the first, you're fine, but even then I wouldn't do if (piece) .. that's kind of an old school (and unclear) way of doing checks.. it's valid but kind of clunky
monobehavior
then yeah, "double-don't" do if (piece)
that's not your exact problem but if you don't your way around c# and unity and why not to do it - just take my word for it, it'll be something that gets you when you least expect it. š
it's kinda like a safety on a gun.. you don't need it until you need it but when you need it, you'll wish you knew about it
sure, thanks
before i start working on this, does this piece of code support choice made by clicking buttons? i don't really use enums
no but that's "easy" enough to solve by keeping track internally which piece is promoting
you have some other problems here in your code - like you have "only one" queen/rook/bishop/knight game object but obviously you can have more than one
or maybe those game objects are the popup "select which piece to promote" objects? if so, disregard
oh, yeah, they are, i see - "rook choose"
so i tried adjusting it, i got couple errors from that, but again, im not really yet good at managing other people code when they use different techniques ```internal enum PromotionType { Queen, Rook, Bishop, Knight, }
public void PromoteQueen(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Queen);
public void PromoteRook(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Rook);
public void PromoteBishop(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Bishop);
public void PromoteKnight(Piece selectedPiece) => PromotePiece(selectedPiece, PromotionType.Knight);
private void PromotePiece(Piece selectedPiece, PromotionType promotionType)
{
TakePiece(piece);
Queen.SetActive(true);
Bishop.SetActive(true);
Knight.SetActive(true);
Rook.SetActive(true);
// remember to grab the square, team first
Vector2Int coords = selectedPiece.occupiedSquare;
TeamType team = selectedPiece.team;
TakePiece(selectedPiece);
chessController.CreatePiece(coords, team, promotionType);
}```
nevermind š but to make your code a little less verbose, I'd parent them all under one game object and just show/hide that.. ie, something like "Select Piece Dialog" and then just turn that entire game object on/off instead of turning each of those objects on and off
yeah, it's not going to work directly - i didn't realize you had tied those game objects to PromoteQueen() etc
I don't quite see how you're tracking the piece that's promoting, but if you have a reference to it somewhere then just remove that parameter
well, it should look like this in game: Pawn reaches promotion, it is killed, 4 buttons appear, when player clicks one of them the piece is placed here
internal enum PromotionType { Queen, Rook, Bishop, Knight, }
public void PromoteQueen() => PromotePiece(PromotionType.Queen);
public void PromoteRook() => PromotePiece(PromotionType.Rook);
public void PromoteBishop() => PromotePiece(PromotionType.Bishop);
public void PromoteKnight() => PromotePiece(PromotionType.Knight);
right so... when the promotion dialog comes up, keep track of what the promotion square is, and based on what the user clicks, place a piece of that type on that square.. map the game objects button on click to PromoteQueen() for the queen button, rook for rook, knight for knight, etc
god i already see sleepless (k)nights when i will try to make 90 cards affecting movement and board shrinking etc
then your PromotePiece() method will take the type it's promoting to as a parameter
heh, well, you'll get there.. your code is a little wobbly and "hard coded" for different situations for now but .. just keep coding, just keep asking questions and you'll learn some of this stuff
then you'll have to work on the stockfish part of the code š
it currently looks like that in unity when i do it with my old not working code
ill ofc add something to prevent playing until chosen
when one button is picked, rest disappers
and the piece is spawned
right type of piece, just position and color are wrong
well, i just finished tutorial by basically copying the code bcs i needed to hand over some progress
and now im trying to understand how it works
i have created a 2d small game before so atleast i know what to do where in unity alone lol, but from coding im still weak
heh.. well.. there's a lot to programming to be fair, and school/learning ain't easy, but .. just go slow when you bulk copy something else because if you don't understand how every single line works, then changing things will be an exercise in frustration
yep, but more frustration would be writing chess from 0 when it is already done, then looking at tutorials for help that does it differently lol
something else i would do that I noticed in your example that are going to be bugs waiting to happen - put brackets around your if/else clauses.. it's "legal" do omit them but the compiler isn't going to help you out when you do something like this:
if (something)
DoOneThing();
else
DoSomethingElse();
//.. then you decide to ...
if (something)
DoOneThing();
AlsoDoThisOtherThing(); // this is a bug!
it is a shortcut for my part of tarot chess cards that i won't get any help in terms of tutorials
you're allowed to use whatever information you want on the internet (including chatgpt).. but just be aware that if you're just "trying to make it work" by copying the bulk of it from somewhere else and then fiddling with random lines of code.. well.. you're gonna hate programming real quick that way.. instead, try to really understand what every single line does and if something isn't working like you expect.. breaking the problem down more and more until you find out what assumption you made is wrong. š
(but also, chatgpt is generally garbage for helping since it just spits out wrong answers with confidence)
i would do it, i just don't have time for this, as school takes like 10h a day
the other 8 is sleep
yeah, but also, there's no real shortcut for learning :p
i know, but it is the only way i can achieve something in good time
lemme maybe restate the ... strategy? Spend like 50% or more of your time strictly learning - just reading, absorbing, trying things out, testing things.. and if you spend that time well, the other 50% where you're actually not trying to learn but just trying to produce something will go way more smoothly. If you start with trying to do something first without knowing how to do it, it's just gonna be.. nightmares and take twice as long
programming as a career is basically carving out time specifically for learning some piece of tech.. it never ends, honestly, even if you are an expert in some area
i've been programming for more than 3 decades and i still google inane shit like "how to initialize an array of characters" or whatever
well, i got badly injured and had to skip school for few months, and i programmed this thing: https://goshire.itch.io/undying-faith So its not like i have no idea what am i doing, i would learn commands but i find that im bored after 15 minutes, thats why im barely passing from grade to grade.
And that quickly demotivates me to do anything, as im constantly tired, and doing boring things while tired is ..... it isn't
two suggestions: coffee and ADHD diagnosis and meds š
or honestly, real hard self assessment if you want to program as a life choice.. programming is fun for some and torture for others.. once you have enough skill and tools under control though, the dopamine hits are there.. it's like small problem solving over and over and over and it feels great when things work and you know how to accomplish things
well, im almost sure i have adhd, also im in one of the most requiring schools in the city, so maeby coffee really is a way, i just don't want to get addicted so early lol
coffee addiction is underrated
i love doing, i hate reading how to do it lol
unless im doing something and solving by reading
like programming
that is why i hate school, you never do, you always read
yeah well.. that's a part of it .. just mashing into doing things in programming doesn't always work all that well. I dunno, there's lots of people who make careers out of programming and don't often read the docs but.. if you can learn to enjoy that part of the process then it'll be a much more rewarding engagement
you have a whole life of "doing" in front of you.. enjoy the "just read" part of it while you still can :p
anyway i'm gonna homer-into-the-bushes here.. I think we hijacked the channel a bit to have this life convo. š
glgl on your chess project
yea, i gtg, school bus is going in 15, ill just show what i have done so far, its not like im not doing 3x more than any other of my classmates in terms of game dev
ill dm you later about this if you can
thanks for help
see you later!
Hello. Does anyone know how to adequately raise some part of the UI when the keyboard appears on the mobile (I enter text into TMP_InputField)? The issue is not the raising itself. But the question is how to determine the height of the keyboard on Android and raise it if this keyboard appears
This```cs
t.position = new Vector3(1000, 10, 50);
Debug.Log($"Mesh Renderer pos: {t.position}");
Huh??
Did you save your code?
simple question: if i want to have a sound when a bullet hits metal, and spawn spark particles, where do i put the code? not in the bullet right,
You could put that even in the bullet
You should do OnTriggerEnter or OnCollisionEnter btw
in my head this is weird when every bullet has a reference to the sound effect, an audiosource and a particle system
yeah no i am not that much of a beginner i was just not sure where to put it
This is the easiest solution, but this works only if the script is attached to the bullet or the wall
More like a reference to a prefab with those things or to an object pool manager
Does anyone know how to customize the appearance of the keyboard for text input in a field? So as not to write in this strange field
Do I have to configure this natively anyway?
I believe you have to learn to love to solve problems. At the same time, it helps to set yourself tiny achievable goals to get a sense of progression
I have a problem with OnMouseOver and using Colliders.
So I placed a BoxCollider in my Armature root (to ensure the Box Collider will adhere to the animation transformations).
The BoxCollider is a Trigger.
So when I hover over the GameObject now nothing happens.
When I put the BoxCollider at the same level as the GameObject where the Component is located of the OnMouseOver logic -> it works.
However there is one way I can make the BoxCollider work when it is placed in the Armature root. It works if I add a RigidBody component to the GameObject. Then for some reason OnMouseOver works with the BoxCollider no matter how deep it is nested in the GameObject's child hierarchy.
Can someone explain to me why that works? I find it not very intuitive.
Can always do raycasting/raycastall and sort it all out easier with layering/tags/comparisons
Presumably, the colliders are moved during the animation. And all moving objects needs a rigidbody for physics to process them correctly. Hard to say what exactly is happening when it doesn't work. Probably the physics representation of the collider is not updated in timed manner causing the event system to miss them during raycasting.
I think you will find the following is happening
No Rigidbody in hierarcy - > collision registered on object which contains the collider
Rigidbody in hierarchy -> collision registered on object with collider and registered on the object with rigidbody
Note: If the object with the rigidbody also has a collider it will register for both
I have a very large navmesh. How can I limit my navmesh agent to only a specific zone/area on the navmesh (so my enemies won't leave their area)? Do I need multiple navmeshes or can I somehow constrain an agent to an area?
Just don't set it's destination outside of the desired area
https://github.com/Unity-Technologies/NavMeshComponents/blob/master/Documentation/NavMeshModifier.md
this is the old system but should still work with the new one, the old docs are much better to learn from
ah interesting - did not thought about that
Well i initially planned getting up 2.5h earlier than i must to program my card chess everyday and be done in few months
Just for the biggest competition in my school
With important members of many IT companies
But i dont think ill make it till then with overload of work from school
But well, 2 months left
why canāt I press the normal send button when shifting?? Well, or maybe you can somehow remove Deselect and the disappearance of the keyboard when you tap on the send button
Is there any magical component that I can store information (variables) in without making a whole script?
What do you suggest that magic script do to know what variables it should even be storing?
Just make a new script.
i was hoping an external single script could access the info stored in many gameobjects throughout my game's hierarchy
make it
will having many scripts affect performance? that's the only reason i was averse to it
this isn't the 1980s
what your scripts do matters, how many of them there are? not so much
that's reassuring! i'll implement it immediately
best not to worry about performance until it becomes a problem
i guess that time i had 300 scripts, it was because of what they were doing that i froze
yep, definitely

If a script is a MonoBehaviour and has empty Update functions, or other Unity functions that are not used (assuming the script and object its on are enabled), this will affect performance, so as long as your 300+ scripts remain clean and only have code its actually using, and your not doing anything taxing in Update, you should be fine, having many scripts in general is a common workflow, and tends to happen with inheritance based programming as well
Just to note as well, if a magical component existed to do what you initially asked, it would run slower than just making a new script that already defines the data it needs.
You really can run a LOT in unity. If your performance is suffering, it's usually gonna be due to a few specific pieces of code which have to do expensive calculations.
^ and for all your performance concerns, theres always the Profiler to track down those specific scripts, if its even script related (sometimes it could be related to rendering, physics, lights, etc, the Profiler can also catch that kind of stuff and even be attached to builds)
How to serialize Textures in a persistent manner?
to know that unity can do so well with scripts is really reassuring!
Texture data is just a byte array which System.IO.File can handle easily
Doenst unity have some sort of Resource folder for this too?
yes but that is editor only
ok
How can i best save this with JsonUtility?
As it stance, Json Utility merely saves the instanceID (non-persistent)
you really do not want to save Texture data using JSON
Ok, it is recommended I use custom saving method for such things
I am making a 2d map. Should I put all the textures/sprites im gonna use in one scriptable container and save everything therer
is this procedural? in Editor? Runtime?
procedural..ish, its a 2d grid map. User will be able to stack textures* and sprites on one hex.
what does that have to do with serializing Textures?
I need to save the map
its a 2d square/hex map, made from sprites and textures at runtime
so the map is a Texture itself?
well once you've made the map you do not need the source textures, you just need to save the map
yes, but the map can be modified
for example, the grass texture, might it turn turn to snow etc
so, when it changes you save it again
the other option is not to have the map as a texture but as a series of data points
yea, that is what Im doing
I was asking if the best strategy was just to save ALL textures in one Scriptableobject
then serialize them from there
but you dont need to do that, your source textures are already in your project
ok, then how do i access them in build?
several ways, you can have references to them in a MonoBehaviour or ScriptableObject or load them using Resources.Load
I see
none of that has anything to do with you serializing Textures
I had used Json.utitly, and it saved the instance ID
Im guessing, I need to make this class Monobehavior then
Unless you're like doing graffiti and painting on the texture to create a whole new texture, but otherwise you're just looking at serializing IDs
ok
don't serialize by instance IDs though as they change between runtime
usually just generate your own GUID, otherwise asset IDs
It's better just to create a new ID honestly and make your own lookup table for them
ok
you don't even need to do that. if you have a ScriptableObject which holds a List of your source textures then you only need to serialize for each hex in your grid a position and an index into that List
that sounds pretty good too
I know what I can/must do now
Thank you very much @knotty sun @latent latch
just to confirm, Transform.GetChild follows hierarchy.. right?
or is it one of those random thingx
things
GetChild takes an index into the children hierarchy, so yes

public GameObject previousPipe;
// Start is called before the first frame update
void Start() {}
// Update is called once per frame
void Update()
{
float distance = Vector3.Distance(previousPipe.transform.position,currentPipe.transform.position);
}
void spawnPipe()
{
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
previousPipe = currentPipe;
GameObject newPipe = Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint)), transform.rotation);
newPipe.name = $"Pipe_{pipeID}";
currentPipe = newPipe.name;
pipeID += 1;
}```
Currently trying to create a Pipe Spawner for my flappy bird game. I am trying to provide a new name that runs the format of `Pipe_{IDNum}`. Whenever one is made it is set to the currentPipe and the former one is set to the previousPipe. My problem right now is finding the distance between them in my update function. If I set it to anything other than a gameObject variable then it will error out. But anything different and it doesn't allow methods. I need it to, when running currentPipe.transform.Position, to give me the position of the current gameObject Pipe it saved? Is there a good way to fix my code to achieve this?
currentPipe = newPipe.name;
cannot set GameObject to string
hmmm. Am I able to convert the name to a GameObject somehow? Cause I need the name to call the object
newPipe is already a GameObject
So just put newPipe itself there?
yes, that would seem obvious
your IDE should be highlighting this as an error. If it is not you need to configure it
It does highlight it, I just didn't know that I could use newPipe to that far of a scope
Hi.
I have these functions for my player movement and for a knockback effect (yes, I will put the knockback for the enemy to deal, not the player in a later time).
https://pastebin.com/zjDRqH5U
It works fine, but I feel like this is a cheap solution
if (isHit)
{
rbody.velocity = Vector2.ClampMagnitude(rbody.velocity, maxSpeed + 5);
}
else
{
rbody.velocity = Vector2.ClampMagnitude(rbody.velocity, maxSpeed);
}
isHit = false;
I need this otherwise the knockback will be clamped to the max velocity when moving. Is there a better way to do this?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
If I ever want to have different knockback forces, this solution would actually be a pain
@celest iron If it works as intended, then maybe don't overthink it.
It's hard to give feedback if we don't understand the motives behind wanting to clamp your velocity. In theory, you're not supposed to manipulate velocities directly. You are supposed to tune your physics simulation so that you get the behaviour that you want with a combination of mass and drag values, along with adding proper forces.
That being said, game dev is game dev and the idea is to take a rocket to the moon. You can absolutely do what you are doing but you need to account for all potential bias without relying on the engine to do so for you, since like I mentioned, it's not designed with the idea that you'll manipulate the velocities directly.
If you want to have different knockback forces, then yeah, manipulating velocities directly is taking the highway towards a headache.
But how am I supposed to clamp the velocity to a max velocity then?
Otherwise it will just fly away
Then the forces applied relative to the mass and the drag you are using are likely very unrealistic
Well, using linear drag did seem to be better
Is there a way of suppressing unity from drawing a certain transform gizmo? I am particularly interested if I can draw a custom gizmo for scale if there is some specific component added by me
disabling the object will do it
so adding the gizmo script on an independent object if you don't want to affect the actual object
or rather I guess you can just disable it as a standalone component
oh im reading this wrong. Yeah, you can disable transform tools pretty easily
via editor script
can also be used to override the build in tools
is there a way to make the trail renderer be relative to the size of the sprite without code, or should i be putting it in a script
it seems to be too wide by default, and if i change the scale of the object, it seems to remain the same
hey everyone, so i have some weapon sway and im now trying to get aiming down sights to work. The problem is, when i try to aim down sights the gun becomes very jittery and glitches around. Anyone know why this might be happening?
wpnPos = restPos;
void CalculateWeaponPos()
{
leanMove.x = leanMoveAmount * movementController.inputLean;
leanMove = Vector3.SmoothDamp(leanMove, Vector3.zero, ref leanMoveVelocity, leanMoveSmoothing);
newLeanMove = Vector3.SmoothDamp(newLeanMove, leanMove, ref newLeanMoveVelocity, leanMoveSmoothing);
movementMove.x = movementMoveAmount * movementController.inputMovement.x;
movementMove.z = movementMoveAmount * movementController.inputMovement.y;
movementMove = Vector3.SmoothDamp(movementMove, Vector3.zero, ref movementMoveVelocity, movementMoveSmoothing);
newMovementMove = Vector3.SmoothDamp(newMovementMove, movementMove, ref newMovementMoveVelocity, movementMoveSmoothing);
wpnPos += newLeanMove + newMovementMove;
}```
```cs
void CalculateAim()
{
var targetPosition = Vector3.zero;
if(movementController.isAiming)
{
targetPosition = movementController.camHolder.position;
}
weaponAimPos = Vector3.zero;
weaponAimPos = Vector3.SmoothDamp(weaponAimPos, targetPosition, ref weaponAimPosVelocity, aimingInTime);
wpnPos += weaponAimPos;
}```
and after that i just do transform.SetLocalPositionAndRotation(wpnPos, Quaternion.Euler(wpnRot));
nvm, i got it. shouldnt be setting weaponAimPos to zero every frame lmao
I'm not sure what the issue is here, but in the past I've usually solved this by moving two separate transforms. For example you could have one that just moves from hip to ads, and then another object as a child with weapon sway. Then when you enter ADS you could scale the weapon sway down to zero so that it stays locked.
Sweet, well if that works for you!
But yes, that is obviously wrong in your code haha
Sometimes having multiple objects makes things a bit easier to reason about
Yeah, this is a great strategy.
I use it to figure out how to move a parent so that a child winds up with a specific position and rotation
Is there anyone who have any experience with abstract classes??
So I have an abstract which called base and have three scripts which derived from it, so i make a list of the abstract base, but i don't know how to called a specific script in the base list..
I hope you understand what i mean
The whole point of abstract classes is that you don't need to "call a specific script in the base list"
Back up and explain what you are trying to do.
And how you are trying to do it.
What you are asking about is possible but likely not the best or cleanest way to do things, and kind of defeats the purpose.
I'll try to explain it i a better way
For example I have the base
Public abstract class base : monobehavior
{
// base
}
And there's a bunch of scripts derived from it
Public class A : base
{
srting name = " cat";
int index = 1;
}
Public class B : base
{
srting name = " dog";
int index = 2;
}
Public class C : base
{
srting name = " fish";
int index = 3;
}
And then there's a manager scripts
Which has a list of A,B and C scripts
Public class manager : monobehavior
{
Public List<base> bases;
}
So my question should be, am i able to get the value from the script B using foreach loop, or even remove the B script from the list
The value you need should be exposed in a property or method on the abstract class
you should not be defining "name" and "index" separately on each child class
it should be like:
public abstract class Animal {
public abstract string name { get; }
}
public class Fish : Animal {
public override string name => "fish";
}```
then you can access name from your base class references
Each scripts has its own methods and values, and i want to access these value, am i able to, or am i using the abstract in a wrong way
You are using abstract in the wrong way if you want to access something that is not common to all of them
why do you want to access them?
What will you do with that information?
The concrete reality of what you're trying to do is important, we cannot gloss over it
It sounds like you are trying to do things in the wrong place.
iām not sure. in this case, he just isnāt using the part where itās abstract, because the abstract class has nothing
the point of an abstract class is to have an implementation that is common to all children, and/or define fields common to all children
but if your abstract class is empty, you arenāt doing anything.
Okey I understand it know, thank you very much for your time.
in this case, you could make an interface instead, since you are defining it separately anyway
I'll try it
public interface IMyInterface{
public string name {get; }
public int index {get; }
}
then they all implement IMyInterface, and define a property instead of a field
public class A : IMyInterface {
public string name => ādogā;
public int index => 1;
}
but idk what you want to do exactly
When i return to my house, I'll tell what i wanna do exactly
Hey guys. Im drawing some random lines now and im wondering if there is a way I can try and retry this random algorithm without running the game? Its so slow on my macbook and takes a long time to run the game
Can execute in editor but ideally make yourself a new project if the current one takes too long to start up
Or just create a button that reruns it
Hello
Maybe you know how you can block Deselect from the input field when you click on some buttons, so that the keyboard does not hide?
I was thinking of doing something like this crutch filtering
and in filters check EventSystem.current.currentSelectedGameObject
but in this case I always have inputfield in currentSelectedGameObject
I've made a tilt script, and it works, but it doesn't tilt relative to the player's rotation, how would I fix it? It only works if I look straight forward on the X, but not in between.
This is all the code that makes it work.
could anyone help with trying to optimise this code? the game freezes for a second before spawning a object?
its the positon/ distance between the object checking that makes it lag
my object pool aswell that links with the spawner
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
could anyone help with optimisation? i just cant figure anything out even with AI.
freeze for second?
do{
randomPosition = Random.insideUnitCircle * spawnRadius;
} while (randomPosition.magnitude < innerRadius);
do{
int val=random.range(0,100);
}while(val<10);
btw when the game freezes for second? in which method?
like i think they are trying to get a random point in a ring instead of just a radius
but there are much better ways to do that, that do not involve looping till it just happens to be right
could you explain how i can get rid of the loops?
it started to lag after i added the ispositionValid
you first get a random direction with Random.insideUnitCircle
then you multiply that by a number, you get from Random.Range(minRadius, maxRadius)
boom random point betwene 2 radiuses no loop
how large the spawnedPositions is?
btw you can use physics system to query a point, dont iterate a set of points without any space partitioning
while loop bad
alos yeah way better ways to do is valid position too
and even if doing it that way dont comapre distance but use sqrmagiutude
persnally i would use the phyiscs system
got your check circle and check sphere methods
i should have put this in code beginner or maybe im over tierd lol. so i need to get rid of the loop and use circle radius checks?
why can TryGetComponent be called as TryGetComponent<MyMono>(out MyMono x) with or without <MyMono> type argument?
do you guys have an idea of how i could make an editor for my rhythm game?
the compiler can infer the generic type from the argument supplied
The analyzer is smart, and can infer the types from the arguments you pass to it, most of the time. When it can't, it'll report an error asking you to specify the generic type arguments explicitly.
something that can adjust the distance between the notes when the bpm is changed
Depends on the game, I guess?
If it's one of those where you need to hit 4-5 notes at most, then you can have some sort of horizontal scrollbar to scroll through the music, place guidelines depeding on BPM, and if you want to push it, automatically determine where to place notes by analyzing the audio file
public GameObject previousPipe;
// Start is called before the first frame update
void Start()
{
spawnPipe();
}
// Update is called once per frame
void Update()
{
if (currentPipe == null || previousPipe == null) { return; }
float distance = Vector3.Distance(previousPipe.transform.position,currentPipe.transform.position);
Debug.Log(distance);
if (distance > distanceFromLastPipe)
{
Debug.Log("Pipe's are far enough for another to spawn!");
spawnPipe();
}
}
void spawnPipe()
{
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
if (currentPipe != null)
{
previousPipe = currentPipe;
Debug.Log(previousPipe);
}
GameObject newPipe = Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint)), transform.rotation);
newPipe.name = $"Pipe_{pipeID}";
currentPipe = newPipe;
Debug.Log(currentPipe);
pipeID += 1;
}```
I was hoping to get some feedback on my code here. I am trying to get a pipe to spawn when they are 50 apart in the x direction. Currently I am finding that distance based on the object that was the previous pipe and current pipe. My problem is spawning in the pipes in the first place. I can easily get the first pipe to spawn in but the second one doesn't work with my update loop. Is there a better way to design this? Or should I keep it and add a line that finds the distance of the right hand side of the main cam to the pipe set in currentPipe to find when I need to spawn a second one. for the start program
There are lots of existing BMS editors out there⦠if you want to suffer having to work with the garbage format that is BMS. Otherwise write your own editor for your own sanity.
cool
ty guys
also, is there a quick way (like O(1)) way to truncate a list? Like RemoveRange, but I actually just want to effectively assign a smaller .Count?
If you don't need the elements in the list, you can initialize a new one with a smaller capacity . . .
Doesnt really make sense to have a method that is O(1) here, you can keep your own int which keeps track of how much of the list should be used.
Although that introduces complexity
but that wonāt be aligned to .Count
then just use RemoveRange
i donāt want to allocate anything
But an O(1) wouldn't make sense if there are multiple elements to remove . . .
you can obviously implement your own list
The only part of RemoveRange when removing from the end that isn't O(1) is the clearing of the removed elements in the internal array. There's no allocation and no copies when using RemoveRange to remove elements from the end of the array.
would removerange do any additional work? beyond setting the count lower, in this case?
It decreases Count and calls Array.Clear to clear the elements that were removed.
i see
You're effectively reusing the same list with a smaller memory footprint . . .
Sounds like pre pre mature optimization. You arent getting a better method that does magic here
yes. . .
The Array.Clear isn't strictly necessary for value type Lists, but definitely necessary for reference types, so there isn't a hanging reference preventing the objects from being garbage collected.
iām tryingn to make something that gets called a lot on a lot of tiny lists, and i donāt like how LINQ effectively allocates a whole HashSet/Dictionary and brand new list for each of its functions for this
ok. i can live with that explanation. RemoveRange it is then. ty all
But even if you decrease the count, the previous memory is still in use if the Capacity is beyond a certain threshold. You have to use TrimExcess to reduce it . . .
I don't think memory is the main concern here
hey i want to upload my game on play store but the aab file needs to be less than 200mb, i think i need to use play asset delivery to lower the size of my game but i dont know how. does anyone have any idea how to use it ? or if not is there any other way to lower the size of my game to 200 mb, right now its like 1gb or something, i did some compression but it wasnt enough
unfortunately itch does have to worry about 3rd world internet. at least for webgl games 
I ran into an issue where i had a file in my webgl zip that was 233mb when uncompressed and itch wouldn't play it
of course that really only applies to webgl games, but they do still have a 1gb limit for uploads
trying to change the amount of particles emitted per second in runtime but these 2 lines of code dont work? this seems right to me and idk what else it could be. does anyone know how to fix this?
are you certain this code is running? and that you are referencing the particle system you are attempting to change?
iirc you need to assign the modules back after since they are structs
https://docs.unity3d.com/ScriptReference/ParticleSystem-emission.html
Particle System modules do not need to be reassigned back to the system; they are interfaces and not independent objects.
oh nice, was that an old thing?
it's been like that as long as i remember š¤·āāļø
hey do you know where i can clear my project & gi cache manually? like where it's located in my system files?
I was editing a prefab instance, and my editor crashed, and now it wont start. I believe clearing the cache might fix the issue but not sure where it is and which files are safe to remove
Is there a dumb way to not invalidate package cache for a particular package [it is my own package]? [without copying it somewhere else or into local]
you can avoid invalidating the package cache by not modifying the package. otherwise you need to embed the package in the project if you want to modify it
meh. why is there not an easy way to load assets in editor outside Assets !! Packages was one hope, but that seems to trigger a package cache invalidation
is it safe to delete %LOCALAPPDATA%\Unity\cache ?
no
maybe restarting will help...
T_T
Native Crash Reporting
=================================================================
Got a UNKNOWN while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
=================================================================
Managed Stacktrace:
=================================================================
at <unknown> <0xffffffff>
at UnityEditor.SceneManagement.EditorSceneManager:LoadLastSceneManagerSetup <0x00086>
at UnityEditor.EditorApplication:Internal_RestoreLastOpenedScenes <0x001ea>
at System.Object:runtime_invoke_void <0x00084>
=================================================================```
im attempting to install a newer version of the editor, but i suspect it won't fix it...
since it probably shares same cache
consider deleting the Library folder in the project
it's built from your assets and also caches stuff like shader variants
Deleting it will require a full re-import of all of your assets.
Do you think changing the editor version to newest is a safer option as a first try? This is what it says it will do:
i would focus on resolving the issues with what you currently have before introducing more unknown variables
do what fen said (and remember that anything you are afraid to delete, you can make a backup copy of first)
ok thanks, will try
If the problem persists, then you can try bumping the editor version
that is, the newest minor release
if you're on 2022.1.2, you can go to 2022.1.3, 2022.1.4, etc.
x.y.z -> change z, don't change x or y
ok so, it loads now, until I try to open the offending scene
and then the same crash happens
so, i think the prefab somehow got corrupted in that scene? not sure
That's what one thread says online, when I search for the error message. Inspect the logs, on their end there was a syntax error in a YAML file (asset file format) which caused the crash on load
Hmm...~~ the interesting thing is the prefab I was editing doesn't appear to be in my Asset library anymore~~
Edit: this appears to be wrong looking at my source control history
Hi
Whenever I try to install my app, it says 'App is not compatible with this version'
No errors in console, nor when testing in unity
is there a code question here?
I was about to call you a minimodder
Then I saw someone else already did before š¤£
hey if you want to misuse channels and be obnoxious that's on you š¤·āāļø
maybe we'll get lucky and a mod will mute you. in the meantime though perhaps you should read over #šācode-of-conduct
can you provide the link you're looking at?
might help
Do you work in this server?
i didnt break any of that
yeah you can stop pinging me now. you're being incredibly obnoxious
The context of the error is different, it's on an older version of Unity, but it checks out
https://forum.unity.com/threads/unity-editor-crash-on-start.716690/
Your stacktrace points to there: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/EditorSceneManager.bindings.cs#L254
Then we fall on the C++ engine side, the code isn't accessible, but the exception is happening there
I'm wondering if it's smarter for me to just revert to my last commit and try to work from there... clearly one of my files is corrupted, not really sure which one at this point
Ah, you're using version control!
you could diff the scene file and see what has changed
Not even revert, I think Git is able to checkout (like how you would checkout a branch) but for a specific commit hash
i was thinking of suggesting this, but usually, the answer is "i'm not using version control"

Idk why my brain isnt working, this is so obvious xD
Hey guys?
Anyone have a script for enemy spawn?
Like...
- Amount of enemys to spawn
- spawn radius
- check if them died to spawn again
- give them rigidbody
- give them mesh collider
- give them other scripts (like my enemyAI or enemyStats)
several of these things wouldn't be done via code at all
just spawn prefabs
what Fen said. but also this isn't really the place to get handouts of code. there are plenty of tutorials available for spawning objects (such as enemies), you should probably go find one that covers most or all of what you need
sure an code to define the enemy as prefab in inspector
the mesh collider from them too
and so on
sure, i found on youtube some...but all what i found cover just the radius and prefab...
but why isnt the place for that here? thats code general...so...whats wrong?
enemies prefabs and SO and script for spawning
because we don't just do handouts of code here. nobody wants to make your game for you. we can help you with your implementation if something you are trying isn't working, but this is not the place to just ask someone to give you the code to do something
If all else fails, you could dive into the EditorPrefs to try and change the last opened scene path.
Since the code is open-source you can clearly see the loading logic:
- Retrieve the last opened scene path from
EditorPrefs(that's probably located somewhere on your computer) - If the path is valid, try to open that scene and report errors as needed (execution does not take that path in your case)
- If the path is invalid or empty, load the last opened scene (you get the exception there)
So you could technically at least open your project by providing a valid scene path in the editor prefs before booting Unity up.
The method: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/EditorApplication.cs/#L551, exception occurs on line 584.
what the fuck?
with what words i asked somebody to build my game?
are you in this world? WTF?
here is place to ask for help and i just ask for help so what is your problem?
Anyone have a script for enemy spawn?
was this not the words you used to ask for someone to give you the code
this is not asking for help. this is asking for someone to do it for you
I mean as long as the string is not empty, even if it contains garbage it won't hit the faulty line and load a default scene (hits line 570)
Thanks, I was able to at least open Unity now, using the deletion of my Library folder.
The new crash log I get when I try to open the scene isn't particularly helpful (at least to my eyes)... I can share it here if you want to check it out though.
Apparently the issue isn't with the Scene.unity file... I checked out my last commit (which was working) and it still crashes š¢
Yeah post the log in a paste website, maybe there's something in it!
Of course those were my words...
But in a channel where you can/should ask for help...why shouldn't I do that too?
no matter what you took...either you stop doing it or you share...I want that too𤣠š¤¦āāļø
i'm not asking for someone to build my game for me
yes, i asked someone to build my game for me
https://pastecode.io/s/xevyo0wt
This is from the crash reporting down, the file was too large but if you want to see more, I can figure out a way
There's a slight (sarcasm) nuance between "I have an issue with my code, here is the error and the context" and "work for me"
are you stupid? why are you putting words in my mouth?

I asked for help for 1 script...not for my game...so please come back down to earth!
so which is it, did you or did you not ask someone to make that part of your game for you.
Yup that's one of your asset files that are corrupted. The first row of the stack trace literally says "OpenAsset" so there's no doubt
It would be all too convenient if it actually SAID the name of the asset in question š
Are you 10 years old or why don't you know the difference between "does anyone/does anyone know a way" and "can someone do this for me"?š¤¦āāļø
See if you can search the log file for "syntax", "asset", "invalid". The forum link I posted has the error at the end of the thread, maybe you should search for some of these keywords
you didn't ask if anyone knew a way to do that. you asked for a script to do that. or are you 10 years old and not know the difference?
Ok then I can answer your initial question. To have an amount of enemies to spawn, store the amount. For a spawn radius, store the spawn radius. To check if they died, store if they died. Give them rigidbody (idk how that's related even). Then also give them whatever other components you want.
Now if you need help with specific code then ask
ooh man...always these little kids...come on, go back to the sandbox to play if you want to weigh every word instead of helping...which is what the channel is intended forš¤·āāļø
Yeah Right!
'Anyone have a script for enemy spawn?
Like...
Amount of enemys to spawn
spawn radius
check if them died to spawn again
give them rigidbody
give them mesh collider
give them other scripts (like my enemyAI or enemyStats)'
What a great way to get all the people who help to not help you
we know the difference. Do you?
The little green icon aside their name really indicates that they clearly don't know how things work here, but yet they try to teach people that have been here for years how to help. Great initiative, but as I said it doesn't work like that
Unfortunately nothing is looking helpful with those keywords, do you know if there's a way to expand the scope of the Crash logger at all in settings?
If I could get more info to find the specific asset in question, that would definitely help
Try a search for "unable to parse" altogether or any of these words alone
I guess another solution would be just reset entire project back to last commit
Make sure your search is case-insensitive also
nuttin, sadly
i wont lose much to just go to my last commit... i think i'll just go with that
Yeah do a checkout on the specific commit before reverting it
Each one is assigned a hash, so git checkout <hash> will get you to a specific commit, and git checkout master (or whatever branch is your current) will take you back
If it loads properly with that earlier commit, you can then do a diff between the two to see what changed
i did git checkout <hash> its still crashing
possible new files could be made that are crashing it?
that werent in the last commit?
let me try deleting those new files
Yeah I think that if you have untracked or modified files, it will keep them even when you checkout another branch/commit so you don't lose your modifications
right
So yep if you remove those files and it works again, the fault was in one of the untracked/new/modified ones
public static void CleanList<T>(List<T> rawList, Comparison<T> comparer) {....}
public static void CleanList<T>(List<T> rawList) where T : IComparable
=> CleanList<T>(rawList, T.CompareTo);```
This doesn't work, but I'm trying to automatically reference the CompareTo function that must be defined in an IComparable. How do I do that?
well, still crashing. i could try the nuclear option and just pull the project fresh
Yep, see if it also happens in a new, blank project to rule out an Editor issue
What error do you get, also does it work without the lambda?
the other scenes in the same project load fine :/ so it's definitely something with the assets in that scene, but yea i'm probably not being thorough enough to figure it out, even with the git logs and stuff
i'll just pull the project fresh from the repo
that should work, otherwise i'm out of ideas
lambda worked great. good idea. ty
idk if it's actually a direct ref, if compiler is smart enough
=> CleanList<T>(rawList, (x,y)=>x.CompareTo(y));```
I guess I'm wondering if the compiler is smart enough to optimize this
or if it tries to make a whole new Comparison<T> object every time
I guess you could pull the default comparer for T and pass that to the underlying method: Comparer<T>.Default
It's smart enough to detect whether the type implements IComparable (why not use the generic IComparable<T> instead?) and to return a comparer that uses it
I see. I changed it to the generic version
IComparable.CompareTo is also an instance method so T.CompareTo doesnāt make sense either. But even if it did exist, Unityās C# is not new enough for that feature.
I know it doesn't make sense, but idk how to get a direct ref to that function, instead of making a lambda that does the same thing
I guess it wouldn't be the same, right? I just realized
Static virtual got introduced in C# 11 to support what you try to do with T.CompareTo, and powers things like generic math: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members
Too bad we donāt have it.
it's not like a huge deal. just looking to learn
Yup "static abstract" members in interfaces (the thing that can make an interface force the implementation of a static member) is only available for roughly the latest versions
i'm mad we don't have all the interface functionality
virtual methods and protected members and all that
and please don't say it's a bad pattern. I just want it
Being stuck at C# 9 in Unity while looking at all the shiny new toys in regular .NET projects gives me feelings š
my garbage collector needs to retire
that man has been working the shittiest job for years
and people only complain about how slow he is
give the man a break
If only I had c# 11, I could finally release a game.
Thank god for Github. @simple egret worked with the nuclear reset fortunately
might be a good time to upgrade my Editor since there's definitely bugs with this build..
lol
the exact same action as before
made the exact same crash
i am the definition of insanity
just a PSA:
yes 100%. it's getting the particle system from a child
Hello, does anyone know if Camera.projectionMatrix returns correctly if the camera is orthographic?
Ok, yes it does
Mistake of mine (matrix compositon occurs from right to left)
(in unity)
Hi folk! What's your approach on interface assignments through inspector? I know there are multiple solutions, but which one do you prefer? As you may know, you can't assign values to interface variables through inspector by default
These days i tend to make an enum which uses inspector logic to switch the fields it's displaying because if you actually serialize polymorphic instances you need to be very careful about changing class names/namespaces to avoid breaking them
you would need a SerializableInterface plugin
TNRD made one on openUPM
well there's also https://docs.unity3d.com/ScriptReference/SerializeReference.html
oh look, itās exactly what he wanted

Hey guys! I have a question. How can I match a GameObject's size to the Physics.OverlapSpere's radius? I am making a Tower Defense game and one tower has an ability that when you click a button it freezes enemies that are inside the radius. I couldn't find a way to show the radius to the player. I can use OnDrawGizmos method for debugging but I'd like to show the radius during the gameplay to the player. Thanks in advance!
is anyone able to see whats wrong with this script? its supposed to be able to add cubemaps on objects as shaders but it doesnt work (i didnt make this someone else did and sent it to me)
public class AddCubemap : MonoBehaviour
{
public Cubemap cubemap;
void Start()
{
if (cubemap != null)
{
Renderer rend = GetComponent<Renderer>();
if (rend != null)
{
Material mat = rend.material;
if (mat != null)
{
mat.SetTexture("_Cube", cubemap);
mat.shader = Shader.Find("Skybox/Cubemap"); // Set the shader to use cubemap
}
else
{
Debug.LogWarning("Material not found on this GameObject.");
}
}
else
{
Debug.LogWarning("Renderer component not found on this GameObject.");
}
}
else
{
Debug.LogWarning("Cubemap not assigned to the script.");
}
}
}
Can someone tell me why my update function isnt working?
you cannot yield inside of a method that returns void
This is a script I found online for a realisitic car controller, I've been reading through it to understand how it all works, but, I can't figure out how the hell its getting input from the keyboard to know what to make the car do. They did say they use the old input system, but I'm unsure what that is or what to look for in that case
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Moved to code-beginner as I feel this is the wrong channel
is there a way that I can set a path based on the area the character is in
I'm basically making my character loop around a path and if in a part of the path is interrupted it will reset based on the path coordination
this is a photo of it
What's the path and how are you making your character follow it?
What? "Cool it"?
How are you moving the character?
Im moving the character via the x and y position with physics applied
The z position is always at 0
At start
So how are you making it follow the path?
You said:
I'm basically making my character loop around a path
Oh I wrote that wrong
I'm basically trying to make my character loop around a path and if in a part of the path is interrupted it will reset based on the path coordination
MB
Okay. So, you'd need to define the path somehow
With waypoints for example. Or bezier curves. And if it's interrupted, you just sample the closest position on the path and return it to it
Do you have a example of this
No. But there isn't really much to example.
Well let me try
Maybe this to grasp the concept of waypoints I guess:
https://learn.unity.com/tutorial/waypoints
But the exact implementation would depend heavily on your project context.
Hi team. JOB question. I have a RayCastCommand job. If I complete it in the update loop after scheduling the batch, all good. But if I wait until the LateUpdate to complete it, I start getting some "Native Array deallocated" errors. It should be the same frame, no? Any advice here for what I'm messing up?
and I'm not disposing the native arrays until after I complete the job.