#archived-code-general
1 messages · Page 253 of 1
what has the data got to do with it, if he had used those strings as file names he would have had the exact same problem
That is true, then I would be asking him why are they different files
The point is that storing json in pp is bad
storing anything in pp is far from optimal
I'm struggling to find a way to contain my camera within the game bounds.
If the player gets really high up in a corner of a room or crouches under something small the camera will clip!
Any thoughts on how I can overcome this?
Maybe give the camera a physics collider that do not allow it to pass certain walls or force the camera to move towards particular points when certain conditions are met.
maybe have a CanStand bool which raycasts above your head to see if the player can stand up again
and if the player cant they stay crouched
hoiw are speed lines like this (where instead of following where the camera is looking its angled n the direction of momentum)
i think theyre using trail render?
StartCoroutine(CrosshairAnimationWrapper());
IEnumerator CrosshairAnimationWrapper(int? state = 2, string? animation = "crosshair_big_to_small") {
// do stuff
}
IndexOutOfRangeException: Index was outside the bounds of the array. Could someone help me understand why I am getting this error? This doesn't make sense!
Send the stack trace and all the relevant !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.
stuff on my tile map keeps randomly disappearing and it's really annoying can anyone help?
hey guys, rn i have a script to destroy cubes when hit by tag "weapon", however i want them to destroy after a 5 second delay. i have destroy(gameObject, 5f) in my script on the collisionenter method but the delay does not work
show !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.
right so how do you know that the Destroy is even being called? I see no attempt at debugging in your code
where did you add the debug?
under the destroy(gameobject, 10f) line
ok, so that would suggest that one of the other Destroy calls is taking precedence
Hey, how does onCollisionEnter work with Character Controllers? I tried it and it didnt detect the collision, so now i tried OnControllerColliderHit which too, had no result. Do you guys know what im doing wrong?
OnCollisionEnter will fire when a rigidbody with a non-trigger colliders hits the character controller
You'll receive that message on both sides of the collision
OnCharacterColliderHit fires when a character collider tries to move into a non-trigger collider
That only fires on the character controller side.
The problem here is that the object needs to hit you
If you try to move into a solid object, your motion stops short of the object
and so you never get a collider overlap
I would suggest using a trigger collider here
you will want to put a kinematic rigidbody on the item
Without a rigidbody, the trigger still works...eventually. It's a bit flaky
Would you say using character Controller is worth it at all in that case?
It just feels so weirdly thought out
it's very useful for first person movement, yes
it's just important to understand that it's not a physics object like a rigidbody is
it's just scooting around every time you ask it to Move()
If you want the player to be affected by physics, then you'll probably want to use a rigidbody.
if i load a scene additivley, is there a way to also take that scenes environment and fog settings and applying them to the main scene ?
You'd need to get the environment settings for a non-active scene. I can't find an example of how to do that.
me neither, a scene aperently doesnt have a refrence for its render settings thats why im asking for help
it might be a weird question but, can I add/remove attributes at runtime ?
like an "#if" but for using or not code at runtime
an "attribute" is something like [SerializeField]
yes
These are compiled into your program.
what are you actually trying to accomplish here?
i found the solution
just for explaining why i asked this question : i was using a cool plugin that helps me adding custom stuff to the inspector, there was a sort of "alert box", that i wanted to show only if i meet some conditions.
but i just remembered that the same plugin gives a option to show/hide its custom attributes using a function
Hey so I been reading and doing some of the c# on a website but I want to know what should i be learning so I'm now wasting my time. I'm right now learn about classes but it's hard to wrap my head around the more complicate ways to have classes from polymorphism, abstraction, and interfaces
no on a w3school website
i've been on the website since 12pm yesterday and now got to more complicate stuff
only now things are clicking
microsoft's official docs do a very good job of describing the language and these concepts
hi i need help .. can anyone suuggest what script or method can i use for saving collect gamobject in level and display on another scene
I'm sure they do but I havent gotten this far just by reading it over and over
i don't understand what that means
can I ask a Navmesh Question here?
how do i get the users pc clock time and insert that into code( the game will run in real time)
i have no idea how to code a real time clock let alone how i'd get the information from a user's pc clock
DateTime.Now
depends
on what?
if its a code question or not?
i dont know, maybe
#🤖┃ai-navigation would be the most fitting
no ones active there 😢
but thanks
you should reply so that I get a ping :p
Hi,
Is a delegate an "event" that scripts can subscribe to & trigger ?
How do you set an event and add/remove a subscriber
hey guys, I've looked up a few methods on YouTube for saving data when creating a new save, but they didn't quite meet my needs.
I have a question:
when saving data in JSON text format, how does the Unity hierarchy work? Is it saved? If not, is there any way to save it?
The event keyword makes it so only your class can invoke the event. Other classes can only add or remove, but not directly change the whole delegate chain. A delegate isnt an event.
You can construct from the bottom up by making gameobjects, but ideally you ID a prefab and insert more serialized data into that
You wont be saving entire gameobjects, so there is no sense of hierarchy. It's not handled by default, so if you need to save hierarchy data then you'd need to handle it yourself
I've got some interesting implementation such as moving my gameobject instantiation onto my SOs so I only need to serialize the data object
basically if it's unique custom data then you serialize it raw via structs, otherwise you should have an ID to them so you can just look it up in your load manager
Is it possible to have unity detect mouse clicks outside of play mode? Something like a raycast click without update. I'm trying to build a tool to spawn stuff with the mouse
ofc you can
iirc Event class gives you the mouse clicks
You'll want to make an editor tool
thanks
Does anyone know any links to a first person camera lock-on system that lets the player perform strafing/ circle-strafing around the target? I have a rough script in place, but the movements are inverted whenever I aim more than once in different positions.
The circle Strafing will come as a natural consequence of just doing sideways movement relative to the camera when locked on
i have a class which stores a bunch of stats in the form of a Stat class, but i'm running into a problem in the form of the save getting bigger and bigger the more i add
i don't save the values if a stat doesn't have any values, but it still saves the name
i use json, here's an example of a stat that's saved even though it's blank
"statModifiers": []
},```
what would be a good way to get around this?
i use Newtonsoft with the following settings ```JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
I have a unity project with my friend and I want him to be able to collaborate in it. But Unity Version control seems to be free, tho you need a credit card and we dont have that. Is there a way to share a project without using a credit card/paying something?
Git / Github
alr thx
I've made an animation for the laser but the size of the sprite changes each frame so I'm trying to adjust the collider size per frame, but it's not working too well.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AdjustColliderSize : MonoBehaviour
{
public SpriteRenderer spriteRenderer;
public BoxCollider2D laserCollider;
public Bounds oldSpriteBounds;
public Sprite oldSprite;
public Vector2 originalPosition;
// Start is called before the first frame update
void Start()
{
oldSprite = spriteRenderer.sprite;
oldSpriteBounds = spriteRenderer.sprite.bounds;
originalPosition = laserCollider.gameObject.transform.localPosition;
}
// Update is called once per frame
void Update()
{
//Checks for the new frame
Bounds newSpriteBounds = spriteRenderer.sprite.bounds;
Sprite newSprite = spriteRenderer.sprite;
//Determines if the sprite has changed and changes the collider size based on the new sprite
if (newSprite != oldSprite)
{
laserCollider.size = new Vector2(newSpriteBounds.size.x, newSpriteBounds.size.y);
}
//I hoped to move the sprite back to its original position to account for the size change DOESNT WORK
laserCollider.transform.localPosition = new Vector2(originalPosition.x, (originalPosition.y - newSpriteBounds.size.y));
//Sets the sprite in this frame as the old Sprite
oldSprite = newSprite;
oldSpriteBounds = newSpriteBounds;
}
}
making geometry dash prototype. I'm using the component Constant Force 2D. force X = 4 the rest is set to 0. I have a VelocityClamp script on it which works. The problem I am having is in my playerController script if got a private void OnJump Method() { rigidbodyPlayer.AddForce(jumpHeight * speed); } so i got the 2d square to jump but it resets its velocity. Should I be using somthing other than AddForce? I'm sure there is a way but how would I store the current velocity of x and just add force to y.
can i edit built in code functions unity
something like rigidbody
or on-screen-stick-
https://pastebin.com/fgxGtwCj -- PlayerHealth.cs
https://pastebin.com/9NcV6Zip -- PlayerMovement.cs
anyone know why it does that and how i can fix it? It happens when I keep holding "D" for going right. (ill fix the issue with the animation later)
Do not post the same question in multiple channels.
Most of the code is compiled, so not modifiable, or peeks into the C++ of side of the engine.
You can try inheriting the class to provide your custom implementation, by overriding the methods
hey uhh for the record i deleted it from the other channel ;|
the one up there
I was not replying to you
yeah but i did the same thing
But it also applies
sorry i thought that wasn't for the begginer channel
so i posted it here
so uhh can ya help?
no ones been answering me
idk if its because of the pixel adventure thing
i just dont have anything else to use
have you asked chatgpt already?
Seems like just an animation issue. It's stuck in one state (jumping/falling?) because it's not detecting the ground
no the thing after
you arent supposed to be able to move
and im not holding the button
its doing it on its own
after you hit the spike
after being knocked back theres something like 3 seconds of waiting before you can move
but its doing it on its own
probably something with hitting the spike search after the funcition or in it
There might just be remnant velocity from the last rigidbody.velocity change.
You need to debug if you're still entering the if statement on PlayerMovement, line 48 after hitting a spike
but can i find the code for the funcitions and just rewrite them myself?
The core C# side of Unity is open-source, as well as some packages, so yes. Everything that uses the C++ side is not, you need to pay a license for that
But consider using the easiest way of inheriting and overriding the class you need, to provide your own behavior
It may not be possible (compiler errors, technical restrictions), but worth a try
Like class MyCustomInputField : InputField then see if there are methods you can override
ok I'll try
A lot of the UI classes are very extensible
Bump
this sounds problematic because it's a variable amount of data
The length of the array will be identical for each chunk
The full stride of the entire buffer won't be variable
ah, okay
I'm not experienced enough to know how to implement that, alas. It sounds like something you'd use a constant buffer for.
Gotcha, if anyone know an answer to this, it'd be a big help
would this cause a behavior like Input.GetKey or Input.GetKeyDown
GetKeyDown
aah ok thanks!
yeah that was what I was looking for
though if it was for GetKey I'm guessing it'd be Value?
It depends on how you're actually receiving input
All that this does is define that "Attack" is an action of the Button type
If you want GetKey-ish behavior, you will want to get a reference to the input action and then constantly check if IsPressed() returns true
If you want GetKeyDown behavior, there are many ways to get a function called when the action fires (PlayerInput component, subscribing to the performed event on the input action, checking if WasPressedThisFrame() is true on the input action...)
The Button action type is mostly there to let you have different "press" and "release" thresholds
So you can have a button with a controller trigger binding
That button can go to "pressed" when you pull the trigger all the way
but then only "release" when you release the trigger almost all the way
It also means that performed only fires once, when the trigger pull exceeds the threshold
a Value type action fires the performed event every time the value changes, if I recall correctly
i need to go catch a hisuian typhlosion (very important) so I'll be out for a bit
UnityWebRequest i think
I think that if you setup a server with an asset on it you could download it to unity if that's what you want you could Ask chatgpt for the details and Google the rest
hey how can i fix this, if the player takes damage then stays on the spike it doesnt damage him again
You would have to use a TriggerStay check with some cooldown. This is why games usually launch the player up a bit when you hit spikes, so it can retrigger the collision if you land back down on them.
it does do that but i also have a damage cooldown
like invincibility
so it doesnt work
Sounds like a design timing issue.
If you want the invincibility to be longer, then just keep bouncing them every time they hit the spikes, even when invincible?
You can probably setup a free server on github or something else you could pay like 10$ for server on cloud
If money is the issue
Hello!
How do you make it so that the unity console always scroll to the very bottom, the latest message, as they are logged? Where's the checkbox for that?
Mine does that for a while and after ~300 messages it just gives up
It was on the wishlist in 2009 https://forum.unity.com/threads/using-unitys-console.10539/
So I'm almost certain it must have been implemented by now! where is it ? i can't find it in the context menu near the console
public class ProjectileSO : ScriptableObject
{
[field: SerializeField] public MovementType MovementType { get; private set; }
[SerializeField] private List<Movement> movements = new();
public List<Movement> Movements => movements;
[Serializable]
public class Movement
{
[HideInInspector]
[field: SerializeField] public MovementType MovementType { get; private set; }
[AllowNesting]
[SerializeField, ShowIf("MovementType", MovementType.Linear)]
private Linear linearData;
public Linear LinearData => linearData;
[AllowNesting]
[SerializeField, ShowIf("MovementType", MovementType.Encircling)]
private Encircling encirclingData;
public Encircling EncirclingData => encirclingData;
public class Linear()
public class Encircling()
}
protected void OnValidate()
{
foreach(Movement movement in Movements )
{
movement.MovementType = MovementType; //cannot set state.MovementData.MovementType
}
}
}```
I'm trying to figure out how to keep this immutable and unfortunately I don't believe NaughtyAttributes is enough here. Are there any interfaces which I can utilize here or am I looking at reflection if not a custom editor script?
Another idea is using this method at nested level:
public void SetMovementType(MovementType movementType)
{
#if UNITY_EDITOR
MovementType = movementType;
#else
Debug.LogWarning("SetMovementType called at runtime. This method should only be used in the Editor.");
#endif
}```
But does that seem a little crusty?
https://images-ext-1.discordapp.net/external/cLmlfdRxNMdV10pQJxgmOhaY3KlkA_eFoCKJGBliVr4/https/i.imgur.com/ekznmdV.png?format=webp&quality=lossless&width=1077&height=903
https://images-ext-2.discordapp.net/external/tkfBEyOqxU1ZcZ728Toykq9zl_qpYulUTKSmfM9W9dk/https/i.imgur.com/PA3Rt5K.png?format=webp&quality=lossless&width=1211&height=903
Any suggestions between these two implementations, or perhaps any other patterns I should consider?
I guess a few questions on this would be what's the idea around using interfaces when a lot of the implementations are generally the same? In this example I'd just be copy pasting a lot of the code which feels wrong, but the idea of having multiple classes would be ideal too over checking an enum for its implementation.
- I have a pop-up window.
- the Pop-up window has two panels Step1 and Step2.
- Step2 should replace step11
How do I achieve this from layout perspective? Obviously I can setActive necesasry panel, but how I lay out one behind another?
it renders ok in game, but editing in editor is clunky due to panels being side by side, is there any solution to it?
I have a stencil shader to apply to my sprite renderer (enemy) and another one for my mesh renderer (fov cone)
I want to make it so the enemy's sprite is only visible in the cone shader stencil, but the sprite doesnt display no matter what.
first image is the stencil mask first pass second is the shader attached to the sprite renderer's material. Third image is what happens in game if I turn the first stencil's ZWrite on, yellow boxes are the enemies. You can see the FOV mesh is correctly blocking part of the enemy but the enemy sprite is no matter what, unblocked by fov cone or not, not displaying the sprite.
I think my question is "how do I make a stencil shader that displays the object's sprite if Comp is true"
How could I make an instance prefab get the canvas to life?
Wat?
Wdym by "get the canvas to life"?
Sorry for my English, I'm Spanish, I have an instance of my player at startup, and I need to get the player's life to be able to put it on the canvas. I'm using GameObject.Find("").GetComponentInChildren<>() but it doesn't work for me
dont find it
make a variable on your player to take in HealthHud if you need it on them
and just stick the UI on the scene
An object with that name probably doesn't exist when that line executes.
Or it's not active. Check the docs for the GameObject.Find method.
Actually nevermind that. It doesn't care about object being active it seems.
Assuming the error points to that exact line, the object probably doesn't exist when it's called
If it exists when I click start everything is still there, but I don't know why it doesn't get the reference
Enable "pause on error" in your console. Then when the error happens, check your scene view for the object.
The error is that it does not get the reference when the player is instantiated is a prefab
I don't see the object with that name on your screenshot.
Is that on error pause?
yes
I see that you're doing networking which might be making things even more complicated. You probably want to inject the references from your player instance to anything that might need a reference to it, instead of using find.
Then it probably happens within one frame, but your Find call is executed before the object is spawned.
Ok, I'm going to try to see if it works from OnStartServer.
Honestly, sounds like it's too early for networking if you can't debug that issue on your own.🤷♂️
having an odd issue with coroutines...
coroutine is defined in my base weapon script, baseweapon.cs:
public IEnumerator WeaponCooldown()
{
weaponAction = WeaponState.Firing;
var cooldown = weaponFireRate / 10;
yield return new WaitForSeconds(cooldown);
weaponAction = WeaponState.Idle;
}
I then have sub-scripts that inherit from this base class - however if the player has one of these inherited classes active as their current weapon, the coroutines don't seem to be waitingforseconds / they appear to be stuck in an infinite state, however I can break this state even though the checks to not do this already exist in the base class..
for example:
in baseweapon.cs I have defined my firing here:
public virtual void Fire()
{
if (weaponAction != WeaponState.Idle) return;
if (currentPrimaryAmmo <= 0)
{
needsToReload = true;
return;
}
currentPrimaryAmmo--;
}
and overriding this in my script, pistol.cs:
public class Pistol : BaseWeapon
{
public override void Fire()
{
if (weaponAction != WeaponState.Idle) return;
Debug.Log("pistol firing");
base.Fire();
}
}
however, it always bypasses the check to see what state the weapon is currently in
is there something obvious I'm missing here or?
I'm assuming its either where I'm calling the coroutine from
or just some weird thing I'm missing
coroutines are being called from PlayerShooting.cs, attatched to the player:
public void Reload()
{
StartCoroutine(currentWeapon.Reload());
}
public void Fire()
{
if (currentWeapon == null) return;
currentWeapon.Fire();
StartCoroutine(currentWeapon.WeaponCooldown());
}
why do you have two fire methods here
each current weapon will have its own firing override, i.e. a pistol firing vs a shotgun firing will have their own definitions on the subclasses
the one in playershooting.cs is the function that gets called when mouse1 is clicked
via input system
ah, ok I see it
yeah 
but your player has no cooldown on firing the weapon
rather, you start a coroutine everytime you fire
there's no checking if you're in a cooldown or maybe im sleepin
StartCoroutine(currentWeapon.WeaponCooldown());
calling this from the player, I'm assuming it'd be best to call it from the actual weapon script?
uh, it's up to your design, but usually you have the attack speed/cooldown on the weapon itself so the player isnt stuck cooldown down when swapping weapons
but as I said before, you start a coroutine everytime you fire it seems
you should be checking if you're in cooldown on the player itself in this scenario before calling weapon firing
that's done by this check here:
if (weaponAction != WeaponState.Idle) return;
unless I'm mixing it up - the weapon states are:
- reloading
- idle
- firing
- noammo
so it would require the weapon state to be idle for it to be able to fire in the first place
if you do this:
currentWeapon.Fire();
then even if you return from this:
if (weaponAction != WeaponState.Idle) return;
you're still executing this:
StartCoroutine(currentWeapon.WeaponCooldown());
gotcha
so if I change the fire function on the player to just:
public void Fire()
{
if (currentWeapon == null) return;
currentWeapon.Fire();
}
and then proceed to update the fire function on baseweapon.cs to:
public virtual void Fire()
{
if (weaponAction != WeaponState.Idle) return;
if (currentPrimaryAmmo <= 0)
{
needsToReload = true;
return;
}
currentPrimaryAmmo--;
StartCoroutine(WeaponCooldown());
}
I'm assuming that would circumvent the issue?
if(currentWeapon.Fire())
{
StartCoroutine(currentWeapon.WeaponCooldown());
}```
looks like my method also works
hell yeah
issue resolved
thank you for the input!
ye
sometimes issue resolving is a lot easier just trying to explain the error and give context in a server like this lol
Can anyone help with this?
any tips for slope movement having bumps?
like the player is bumping or smth
using rigid body
yeah that's a little hard but there are physics materials which you can toss on them
or do it my way and not add bumps ;)
Use the layout scope versions and you don't have to think about how they pair up https://docs.unity3d.com/ScriptReference/EditorGUILayout.HorizontalScope.html
Use UI Toolkit and you don't have to think about that shit at all
what's your way
(dont want to use physics materials as im simulating friction in my playermovement)
Anyone got a small infograhpic on how this works?
I could probably just draw it using like lines but maybe its somewhere else
Not sure I get the question. Are you asking about what that code does?
the equation for moveDirection work
It takes a forward and right direction vectors of an object, multiplies them by the input and adds the 2 vectors.
Oh yeah nvm
I just thought about it
What a coincidence, whenever i think about a problem i understand it!
does unity include scripts in build if i dont include them in scene (and dont reference them anyhow)?
it seems it doesnt
from what i read at least
it cleans up quite a bit
still can have unwanted/unused scripts lingering on prefabs
bigger problem is it's heavier assets like textures
Hey, how can I make zenject inject stuff into already existing monobehaviour?
Does anyone know why I'm having this weird effect with the texture fading to white?
what tool you used to drawn diagram ?
Probably mipmaps
What shader are you using for it?
Also, it's not a coding question.
Standard lit
Maybe specular lighting/reflections?
how can i make it not change the scale of the bullethole prefab when its parented to an object?
// Graphics
if (Physics.Raycast(fpsCam.transform.position, direction, out rayHit, range))
{
// Executes if hits a collider
Rigidbody rayHitRigidbody = rayHit.collider.GetComponent<Rigidbody>();
if (rayHitRigidbody != null)
{
Instantiate(bulletHoleGraphic, rayHit.point + rayHit.normal * 0.01f, Quaternion.LookRotation(rayHit.normal, Vector3.up) * Quaternion.Euler(90, 0, 0), rayHit.transform);
}
else
{
Instantiate(bulletHoleGraphic, rayHit.point + rayHit.normal * 0.01f, Quaternion.LookRotation(rayHit.normal, Vector3.up) * Quaternion.Euler(90, 0, 0));
}
}
dont use the parenting option of Instantiate, use .SetParent with worldPositionStays=true after instantiation
ok ty
such a simple fix and its fixed an issue that i didnt want to solve :3 thank you tons!!!
Ok so i created an empty monobehaviour script, and didnt attach it to anything, and it got included in assembly(in the build) regardless
Is there an option for this? I thought it shouldnt be included if its not in scene
i have this on high. I think it removed empty methods from build. but it didnt remove scripts that werent attached to any scene
It certainly should have done. Are you doing a development build? It's possible that the behaviour is different then
no (im testing on a new project too, same result)
Unity strips most unused Assets during the build, so you don’t gain anything by manually removing Assets from the Project. The only Assets that are not removed are scripts (which are generally very small anyway) and Assets in the Resources folder (because Unity can’t determine which of these are needed and which are not).
also found this
Yes, "assets" as used here in the docs unfortunately only refers to non-script assets. For scripts, we have no way of tracking dependencies like for other assets. Some platforms have dead code stripping so unused code is removed but the webplayer and standalones don't do that.
One reason for this is that it is a non-trivial problem. If you are using reflection, for example, it is often quite impossible to tell which scripts you are actually using and which you are not.
And in a sense, since the compiled DLLs will actually include all scripts, the scripts are not actually unused.
How to model this in code:
- I have a "root" game object with a script that generates some asset (in my case shader and updates material, but that's irrelevant for now)
- children of this "root" can be added, removed and their script values modified — the root should react in that case. (In the edit mode, it should update generated shader code, in the runtime it should only update uniforms)
Can someone give me an example code how to do that? I was thinking using OnEnable to find ancestor root and attach to the roots events, and a bunch of events in the root like childChanged which in turn root component listens on and reacts accordingly (update uniforms / regenerate shader if needed)
Basically, what that is saying is that everything written in Managed Code Stripping is untrue
others seem to report similar issues. anyway ill try with #if UNITY_SERVER but would be nice if didnt have to
using platform define or however its called worked for me
I've certainly had to use attributes in the past to stop code being stripped when I didn't want it to be, so maybe something has changed in recent releases
Whatever that's quoting from is probably just using the term script to refer to a MonoBehaviour or ScriptableObject
Also, seems nonsense when it talks about reflection. That's not guarded against when stripping, it's part of the reason reflection is a poor choice at times, because you have to mark the things you care about as preserved
I wonder if there is a difference between Mono backend and IL2CPP because IL2CPP stripping seems to be much more aggressive
There definitely is
Yeah. IL2CPP won't even permit you to disable stripping entirely
Although I wonder if "minimal" stripping just winds up being whatever the AOT compiler decides to remove
It plays merry bloody hell with generic types, I can tell you that
How can I implement camera boundary detection when my camera is tilted 45 degrees on the x-axis? I have tried a couple of methods, but they don’t seem to work. The closest thing I can get is using GeometryUtility.TestPlanesAABB to detect whether or not the player is inside the camera view, but I’m not able to go further.
Hi does anyone use Guids to id things in their game and use a helper class to serialize and handle empty value?
I use GUIDs to identify some categories of objects.
They're all assets, so I just copy unity's GUID over in OnValidate
(not a huge fan of doing all that work every single time validation happens. I might just write an editor tool to copy them over on command instead)
ok this is for like saved data, not assets
but I see some other people have wrapped system guid now. wrapped for serialization
I reference these assets in saved data
(by serializing the GUID as a hex string)
maybe I should switch to writing base64..
what I see people doing is just using a string (System.Guid) guid.ToString() on serialize/deserialize via a wrapper class. In order to use System guid and the fast comparison of that compared to just using strings
I use a custom Guid class that Unity can serialize.
(since System.Guid is not Unity-serializable, for some reason)
yes I saw some here: https://forum.unity.com/threads/cannot-serialize-a-guid-field-in-class.156862/
yeah that seems to save the guid as four values rather than just convert guid to 1 string and save that
i am sorry to interrupt your conversation... what's the matter? i can help you?
I still serialize it as a string when it gets put into a JSON file
I still needed it to be unity-serializable so that I could actually store the value in the asset
as a developer how would you make sure that anyone who edits one of these methods also makes the same edit in the other method?
The problem I'm trying to solve is that while editing a material or material property block produce functionally the same result, they are technically completely different so I haven't been able to write one single unified method
DRY - don't repeat yourself. Is One call simpler than the other? Can one call just call the other?
Yeah I don't want to write duplicate code like this but:
materialPropBlock.SetColor("_Color", colorToApply);
material.SetColor("_Color", colorToApply);
these look like the same method but are completely different classes and methods that happen to share the same name
Maybe there IS some way to write a single method but I couldn't figure out a way
yes I see, not sure of why it must be so, but you could make 1 call that takes a material or a property block and applys to 1 OR the other. Then at least all Set calls are in one place/function
You could make an "adapter" class that accepts either a property block or a material
and presents a consistent interface
then you can hide the ugly repetition in there
I'm doing something like this for my game's "choice" settings. I have many different kinds of choices -- a list of literal Choice assets for my settings system, a list of entities to spawn, a list of maps to load
They all get wrapped up in an IChoiceItem interface that has methods for switching to the next/previous choice, describing the current choice, etc.
...IChoiceItem is a really bad name for something that's multiple items, on second thought
i should fix that
yes Fen's is the pro way! But for speed just have the 2 current calls call 1 function which accepts either material or property block and then do each set call on whichever is not null!!
That makes sense, Ill make a higher level routing class with nulled parameters 
ApplyProperty<T>(string param, Color color) where T: Material, MaterialPropertyBlock {
T.SetColor(param, color);
}
how to stop rigid body player from bouncing when moving on slopes?
this doesn't make sense; that would constrain T to be both a Material and a MaterialPropertyBlock (which is illegal)
Yeah that was my issue, they aren't technically the same thing and are not interchangable, even if the result more or less is
You could subclass both Material and MaterialPropertyBlock and implement an interface with the SetColor/etc. methods in it, then accept an argument of that interface type. But that wouldn't really make any sense, since you'd have to use MyMaterial and MyMaterialPropertyBlock
not very helpful
Hey. I am having a spaceship, which shoots bullets with rb.Addforce(). I want the velocity of the spaceship to be taken into account when shooting the bullet. How do I do that?
Code:
fire.transform.parent = null;
fire.GetComponent<Rigidbody2D>().AddForce(this.transform.up * force);```
add the current velocity of the spaceship to the force?
add force needs Impulse if you want to do it in 1 frame
Yeah.
The default force mode -- ForceMode.Force -- is for continuously applying a force.
ForceMode.Impulse is for an instant "kick"
One second of ForceMode.Force calls is equal to a single ForceMode.Impulse call
I forget if the Force and Acceleration modes misbehave when used in Update
at least in 2D, ForceMode.Impulse directly adds deltaT * force / mass directly to the velocity. Immediately in that line
2D does not delay. It is instant, one line to the next. And no, that is not better.
It SHOULD get delayed so you can read it in different scripts, and see what velocity came in as velocity vs some impulse-added force in the middle.
assuming 3D has a way to read the total impulse force, that is the better way imo
I don't think you can ask for the "pending" force
but yeah, it's generally more annoying when changes apply immediately
that’s suck
copy the game's memory to a file, run until the next physics update, measure the velocity, and restore the game's memory. ezpz
in my custom physics engine, key things you can read include also the next MovePosition, if applicable, for a kinematic RB
my PhysicsMover API just logs shit when it gets external requests
then it combines everything right before physics solve
it is extremely annoying to not be able to read MovePosition, or if there is a current MovePosition at all
it’s okay though. I assume all of Unity’s new staff will fix it. And by new, I mean the ghosts taking over the workstations of all the laid off workers
Howdy folks! I'm watching through a tutorial on using Lobby for multiplayer, and the tutorial creator keeps surrounding everything relating to connecting in joining in try/catch like this:
// Stuff relating to creating or joining lobbies in here
} catch (LobbyServiceException e)
{
Debug.Log(e);
}```
I'm not entirely sure what this is meant to do, as all it does is log the error. Also, is this something I should just keep when testing and remove after, or I leave this in after creating my lobby system?
Hey everyone, I have a bit of a head scratcher. I have a function that updates a little minimap with a color sampled from the terrain as the player crosses it. It works just fine aside from the texture I'm creating having this weird artifacting. The black cross in the middle should not be there, the other two black dots should be. I tried changing the filter mode but no go. Anyone have any ideas? Below is what I'm seeing an the associated code. All outputs are working correctly as far as I can see. It is trying to assign the correct pixel the correct color.
mapTexture = new Texture2D(rs.wc.worldWidth, rs.wc.worldHeight);
// mapTexture.filterMode = FilterMode.Point;
for(var i = 0; i < mapTexture.height; i++){
for(var j = 0; j < mapTexture.width; j++){
mapTexture.SetPixel(i,j, Color.black);
}
}
ApplyTextureChange();
}```
``` public void UpdateMap(Vector2 coords, Color color){
int convertedX = (int)coords.x;
int convertedY = (int)coords.y;
if(coords.x <= 0){
convertedX += rs.wc.worldWidth/2;
} else {
convertedX -= rs.wc.worldWidth/2;
}
if(coords.y <= 0){
convertedY += rs.wc.worldHeight/2;
} else {
convertedY -= rs.wc.worldHeight/2;
}
Debug.Log($"{convertedX} - {convertedY}");
mapTexture.SetPixel(convertedX, convertedY, color);
ApplyTextureChange();
}```
``` void ApplyTextureChange(){
mat.mainTexture = mapTexture;
mapTexture.Apply();
gameObject.SetActive(false);
gameObject.SetActive(true);
}```
try {} catch {} is very basic C#, I suggest reading the docs
If the stuff in Try fails, catch will run and then your code will continue as expected. Without it, if your lobby code breaks, Unity is going to have a fit and chances are your code will stop executing properly. It's just proper exception handling, is all.
I understand what try catch does, I'm just confused on what its purpose is in this situation where it only logs the error.
it stops your program blowing up
Right, but theoretically if things are functioning I shouldn't be getting any errors in my scripts, no? And if it does blow up then the error is still logged and so I go to the error
this is network code, it will always go wrong so you have to deal with it
Gotcha, so should I keep it in my finished product then just to be sure so that if a connection goes wrong or somebody's wifi goes down or anything that the entire game doesn't go up in flames?
exactly
that makes sense, thank you very much!
!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.
Hey, I'm trying to figure out how to get a "audio to fire ONCE when passing over the threshold, then RESET if not in threshold". Problem is, sometimes the range is a mixture of positive and negative. The else if seems to work sometimes, but because it randomizes into the negative range or positive range, a >/< doesn't always work. Any ideas on how to capture the range, then do a != against it?
// Pick can only rotate when not rotating keyhole (keypress)
if (canMoveLockPick)
{
Vector3 dir = Input.mousePosition - cam.WorldToScreenPoint(lockpickTransform.position);
eulerAngle = Vector3.Angle(dir, Vector3.up);
Vector3 cross = Vector3.Cross(Vector3.up, dir);
if (cross.z < 0)
eulerAngle = -eulerAngle;
eulerAngle = Mathf.Clamp(eulerAngle, -maxAngle, maxAngle);
Quaternion rotateTo = Quaternion.AngleAxis(eulerAngle, Vector3.forward);
lockpickTransform.rotation = rotateTo;
// If you pass over pin, then play audio
if (eulerAngle < unlockRange.y && eulerAngle > unlockRange.x)
{
if (!firePinAudio)
{
firePinAudio = true;
// pin audio is quiet
audioSource.volume = tumblerVolume;
audioSource.PlayOneShot(inRangeAudio);
}
}
// If not within range, then reset audio so it can be fired again!
else if (eulerAngle > unlockRange.y && eulerAngle < unlockRange.x)
{
firePinAudio = false;
}
}
Like for example range is 30 - 90; then its -25 to 50, or -25 and -13. I'm not sure how to get the min max threshold range as a variable then invert it as the "reset area"
You can use Mathf.DeltaAngle to ask how far apart two angles are (measured in degrees)
If you specify the unlock range as an angle and an angular width, you can then just check if the angle delta is less than the width
this will let you add an unlock angle that straddles the 180 -> -180 transition
hey guys, I am still stucked on my Coyote Time, when I jump the first time, the hasJumped is not true, it's true after the second jump
https://paste.ofcode.org/38Gj9dNhwfva7gcFjwmPyQX
However I found out, that the issue might be that when I jump the ground check is true for some miliseconds, so it sets the hasJumped back to false even before the whole jump code is ran, idk how to fix it tho, can somebody help me please?
Here's one for y'all: When the player is holding an item, I project a ghost (Instantiated copy with new material) of the item to show where they will place it when they use the Drop action. What would be the cleanest way to have that ghost copy the state of the original object? Say it was a small lockbox and the player opened it - I would want the ghost to also appear opened.
I could brute force this by passing a reference to the original and when I run a method, I check for a ghost and run it on there as well, but I'm not sure how to best make it more systematic so I can easy apply it to all possible types of pickups with different and potentially multiple manipulations possible (an apple with X number of bites out of it / a puzzle box with 3 specific panels opened / etc.)
Been scratching my chin over how best to approach this.
I feel like most games wouldn't go to this level of detail, and unless it's mandatory for gameplay, the player won't even notice that it's the "default state" of the object they're holding.
Oh, I agree. Definitely not neccessary. I'm just a glutton for dumb polish and was curious.
I'd expect it to be similar to however you restore the state after you place the object.
But if it's mandatory, the only way would either be to brute force it as you said, or somehow create a state system for all objects to have? And you drag/drop variations of models to represent a "used" state, "damaged" state, "eaten" state (and leave them blank for things that don't make sense), which in turn would be a list of substates so you can have multiple versions (ie, multiple bites of an apple) with some property value representing which index you're at. Then you iterate and match.
Making your grounding check more conservative would help.
Especially now that you have working 'coyote time'
The original object is just moved from my hand to the new location, no state changes made. The Ghost is the only copy.
ah, I see
what do you suggest?
Actually, you may get away with instantiating the literal version that the player has in their hand rather than a prefab. Depends on how you've modified the object at runtime to be in its current state.
Make the circle smaller or use a short, wide box instead
hmm. yeah. I can experiement with that.
You could also make IsGrounded() return false briefly as long as your vertical velocity is positive
thanks Fen 🙏
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Hey all, any idea as to why my character suddendly stops moving every now and then? The velocity keeps going up and back to 0 when this happens.
dont use time.deltaTime in rigidbodies
also should move using FixedUpdate
no time deltatime?
no they already move with fixed time step
damn okay have been doing that wrong all these years
If anyone would like to help, even after changing my use of delegates this error still occurs
still having my issue
movement code is now this
hey @heady iris sorry for pinging, just wanted to let you know that I solved the issue by changing the (groundCheck != null) to (rb.velocity.y == 0)
copilot haha
okay so
i can move around, but every now and then, even though input is registered, it stays at vel 0
in the video i hover around the values in the editor even though the player is not moving
Ohh
i had this issue also before clamping velocity
how do you get HorizontalInput
that is dangerous
you are subscribing an anonymous function to a delegate that exists for the entirety of your game.
meaning you cannot -= it
ctx =>
kind of in C haha but not in C#
a delegate is like a pointer to functions
anonymous function is function with no name
ask yourself what the name of ctx=>some codes is
the problem is that two identical-looking anonymous functions are still going to be two unrelated objects
so you can't unsubscribe from that event later
[...].canceled -= ctx => HorizontalInput = 0f; will do nothing
So if that is bad practice, why is the new input system praised?
well, don't do the wrong thing
this has nothing to do with the new input system in particular
a delegate is kind like a collection (list) of functions to call when invoked. But it is not actuallt a collection. You can’t .Count, access by index, and there isn’t actually an order
the main reason new input system is fantastic because your methods are only called when you get an input for them
So i would use this for a jump for example?
void OnEnable()
{
upAction.action.Enable();
upAction.action.performed += TryPop;
}
void OnDisable()
{
upAction.action.performed -= TryPop;
}
a little example of subscribing and unsubscribing
old input system requires any anything that checks input to basically check in Update() every single frame, every possible input. And if that method is not in a monobehaviour, you can’t just do it.
when this component is disabled, it removes its TryPop method from the performed delegate
so it's not called at all
ahh okay
for literally anything where you have input, except UI elements where EventSystem is in control of it
This is particularly important if you've turned off Domain Reload and are using things like InputActionReference
otherwise you'll have stale delegates left over from the last play session
but EventSystem also can interface with playerInput components to rewire it anyway
i see
ill have to look a tutorial as well then i guess
dont wanna start off wrong
thanksd guys!
InputSystem also makes it easy to rebind, especially for different control schemes or platforms
There are lots of ways to get input with the new system, which can be a little overwhelming to try and learn all at once
first, learn about delegates. you can’t use InputSystem without it
the two main patterns are:
- .ReadValue<>() to get the current value of an input. This is for something like reading the Vector2 for a control stick, or if a button is down vs up.
- Make a method that takes as an argument InputAction.CallbackContext, and subscribe/unsubscribe this method to the delegates for your player input. So whenever invoked, that method gets called.
I use InputActionReference for most of my code. So things can look like this
moveActionReference.action.ReadValue<Vector2>();
or I can subscribe to events, like this
Does anyone have good unity software pattern design books they'd recommend ?
i almost exclusively subscribe to events. i only ReadValue within the methods invoked in those methods.
not a book but
https://refactoring.guru/
If anyone would like to help, even after changing my use of delegates this error still occurs
i can move around, but every now and then, even though input is registered, it stays at vel 0
in the video i hover around the values in the editor even though the player is not moving
hey can somone let me know how i can create a tilemap on a spritesheet? i converted the sprite sheet to multiple but draging it to the palette doesnt work?
you have to slice it first
also not a code question
yeah i did but forgot to click apply
link the chat im supposed to send in
uh probably #💻┃unity-talk
alright thanks
Can Radio Direction Finding be replicated in Unity?
I was wondering if radio waves can be replicated or simulated in Unity somehow.
I want to make a simulator simulating Radio Direction Finding and was wondering if Unity can replicate radio signals and translate it to UI element based on strength from the 4 antennas
You can replicate anything you want, you just need to code it. It sounds like you'll need some physics casts or overlap checks to do what you want. I think overlap makes more sense given the image
Not sure what translate it to UI elements means though
probably an overlapcircle and a raycast. overlap to check if it is in range, then raycast to attenuate based on distance, penetration through other objects
See the green spots on the plus symbol in the middle it shows what direction its coming from
Yea that as well would be possible. but if all these are UI objects then you're gonna have a harder time detecting nearby objects
You would just use the direction from the radio source and compare it to like up left down right to see what to light up
Ok, I'll start reading up.
Thanks for the insight
If you want more complex radio behavior, like lobes on directional radio sources, that should still be reasonably easy to implement
Now, if you want fully realistic RF...
🫠
(but that's not a Unity issue -- that's just an issue with RF being completely bonkers)
The range of cube left = 3.4, and the range of cube right = 5.6
How in the world is the left circle bigger than the right circle?
private void DrawVision()
{
Vector3[] vertices = new Vector3[resolution + 1];
int[] triangles = new int[resolution * 3];
vertices[0] = Vector3.zero;
float angle = 0;
float angleIncrease = 360f / resolution;
for (int i = 0; i < resolution; i++)
{
Vector3 vertex = Quaternion.AngleAxis(angle, Vector3.up) * Vector3.forward * towerData.GetStat(StatType.Range).value;
vertices[i + 1] = vertex;
if (i != resolution - 1)
{
triangles[i * 3] = 0;
triangles[i * 3 + 1] = i + 1;
triangles[i * 3 + 2] = i + 2;
}
else
{
triangles[i * 3] = 0;
triangles[i * 3 + 1] = i + 1;
triangles[i * 3 + 2] = 1;
}
angle += angleIncrease;
}
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
meshFilter.mesh = mesh;
}```
range being the diameter of the circle
are you confident you have them in the right order
also, to sanity-check it, I would get rid of towerData.GetStat(StatType.Range).value and replace it with a constant
see if the circles have the same size
just
wow they don't 🙂 I feel brainrot
time to find out why they don't ig
You might have an unwanted scale somewhere.
brainrot intesifies, thank you so much 😭 I am done for today
sanity checks save the day!
it's good to remove variables when things are misbehaving
I need a logic check here as something is going wrong and I am unsure what:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[ExecuteAlways]
public class EdgeMarker : MonoBehaviour
{
[SerializeField]
Mesh mf;
[SerializeField]
Transform tf;
List<Edges> edges = new();
#if UNITY_EDITOR
private void OnDrawGizmosSelected()
{
edges = new();
mf = GetComponent<MeshFilter>().sharedMesh;
tf = GetComponent<Transform>().transform;
for (int i = 2; i < mf.triangles.Length; i += 3)
{
bool found = false;
Edges newEdge = new(mf.vertices[mf.triangles[i]], mf.vertices[mf.triangles[i - 1]]);
foreach (Edges e in edges)
{
if (e.Same(newEdge))
{
found = true;
}
}
if (found == false)
{
edges.Add(newEdge);
}
Edges newEdge2 = new(mf.vertices[mf.triangles[i-1]], mf.vertices[mf.triangles[i - 2]]);
foreach (Edges e in edges)
{
if (e.Same(newEdge2))
{
found = true;
}
}
if (found == false)
{
edges.Add(newEdge2);
}
}
/* foreach (Edges e in edges)
{
print(e.ToString());
}*/
print(edges.Count);
foreach (Edges e in edges)
{
Gizmos.DrawLine(
new Vector3(
e.pointOne.x * tf.localScale.x + tf.position.x,
e.pointOne.y * tf.localScale.y + tf.position.y,
e.pointOne.z * tf.localScale.z + tf.position.z),
new Vector3(
e.pointTwo.x * tf.localScale.x + tf.position.x,
e.pointTwo.y * tf.localScale.y + tf.position.y,
e.pointTwo.z * tf.localScale.z + tf.position.z));
}
}
#endif
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Edges
{
public Vector3 pointOne;
public Vector3 pointTwo;
public Edges(Vector3 pOne,Vector3 pTwo)
{
pointOne = pOne;
pointTwo = pTwo;
}
public bool Same(Edges other)
{
if ((this.pointOne.x == other.pointOne.x) && (this.pointOne.y == other.pointOne.y) && (this.pointOne.z == other.pointOne.z))
{
if ((this.pointTwo.x == other.pointTwo.x) && (this.pointTwo.y == other.pointTwo.y) && (this.pointTwo.z == other.pointTwo.z))
{
return true;
}
}
if ((this.pointOne.x == other.pointTwo.x) && (this.pointOne.y == other.pointTwo.y) && (this.pointOne.z == other.pointTwo.z))
{
if ((this.pointTwo.x == other.pointOne.x) && (this.pointTwo.y == other.pointOne.y) && (this.pointTwo.z == other.pointOne.z))
{
return true;
}
}
return false;
}
public override string ToString()
{
return "{ " + pointOne.ToString() + " : " + pointTwo.ToString() + " }";
}
}
I am trying to draw all edges using Gizmos, but the count is incorrect.
Does the triangle array not match per 3 index positions?
If I modify the triangle loop to be positive numbers it works for cubes, but still not on planes:
the triangle array SHOULD indeed be a multiple of 3, each element being an int reference to your vertex array.
Not directly related to your issue but this code is very inefficient.
Yeah, I understand its pretty bad, was going to get it working and then improve, it shouldn't be constantly drawing all of these
and all those float equality checks, a recipe for disaster
for (int i = 2; i < mf.triangles.Length; i += 3) why start at 2?
one big hint:
Every time you do mf.vertices or mf.triangles it creates an entirely new copy of the entire vertex or triangle array from the mesh.
starting at 2. (not a multiple of 3) is gonna give you the wrong points for a given triangle
When creating the edges I used -1 and -2, but if you switch it, it works better.
for (int i = 0; i < mf.triangles.Length; i += 3)
WTF!? good to know!
index is 2 and the array is zero based, so 0,1,2 makes 2 the 3rd.
@leaden ice is that true even if I use
mf = GetComponent<MeshFilter>().sharedMesh;
the shared mesh?
yes it's true
it doesn't matter which mesh it is
yeah, [2] is the last point in the first triangle. is that what you really want?
@clever lagoon Yeah so the logic was poorly made in the first edge and second edge:
Edges newEdge = new(mf.vertices[mf.triangles[i]], mf.vertices[mf.triangles[i - 1]]);
I did switch it to not use negatives and start at 0. This works correctly for cubes, but not planes
ah! your using i-1 and i-2 not i+1 and i+2.. ok starting at 2 works or tat I guess.. jus a bit confuing
I am unsure why all edges are not being drawn in the plane
yeah I agree glurth haha, I swapped it back to normal.
Wouldn't you just do this?
int[] triangles = mesh.triangles;
Vector3[] vertices = mesh.vertices;
for (int i = 0; i < triangles.Length; i += 3) {
Vector3 a = vertices[triangles[i]];
Vector3 b = vertices[triangles[i + 1]];
Vector3 c = vertices[triangles[i + 2]];
Debug.DrawLine(a, b);
Debug.DrawLine(b, c);
Debug.DrawLine(c, a);
}```
not sure why you need more than this
btw, when you say all edges- do you mean the edges of all the triangle, or the "final" edges of the whole plane itself?
for ALL tri's I like Preaetor's answer
So as I understand it the triangle includes duplicate edgeswhere they match the other tris, I was trying to get rid of duplicates.
It's possible depending on the mesh but
if you're just trying to get it to work right now why are you worried about culling duplicates?
got it. thats what the Same() function is for (usually we go with "Equals", but thats just a convention.
that would only be a performance concern basically
hmm... newEdge , newEdge2 .. what about #3?
So like on a quad, there are 2 tris, 4 verts and 6 edges. when I run I want it to show only the 5 edges that you can actually see.
If you want to cull edges make an Edge class and implement Equals and HashCode (not Same) and just throw them in a hashset then draw them all in a simple for loop
what's the difference?
How would you even be able to tell
Start simple
then get complicated
this is C++ 😮
Actually little big let me pastebin it
yeeeah well same logic applies
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I am attempting to visualize WFC edges.
just checked again, you dont generate edge3- perhaps thats why it's not showing up (and finding thier dups)
Ah so you think like instead of going +3, +2 might generate those missing edges?
Let me check
no.. I mean you have newEdge and Edge2 but a trinagle has 3
[i, i-1], [i-1.i-2] but no [i,i-2[
The start of the next edge in the array should be the third edge.
That change made interesting results haha:
Can you just try this quickly? #archived-code-general message
Then you can improve on it if you really want to worry about culling duplicates
hmmm I dont think so. after you i+=3 whatever edges you get using i, i-1 or i-2 will be from the next triangle
@leaden ice There is where I started and it works as intended, but it does not have world space only local.
Convert to world space with transform.TransformPoint(whatever)
you've overcomplicated this
@clever lagoon So you are saying the need for the last index per loop needs to attach to the first:
Edges newEdge3 = new(mf.vertices[mf.triangles[i + 2]], mf.vertices[mf.triangles[i]]);
foreach (Edges e in edges)
{
if (e.Same(newEdge3))
{
found = true;
}
}
if (found == false)
{
edges.Add(newEdge3);
}
Here
@clever lagoon This is why they pay you the big bucks:
But now it broke the cube.
This has everything you want
duplicate edge culling
world space
etc
and much more performant
Nice, let me take a look at HashSets as I am really new to this, but it looks a lot more straight foward.
the hashset is just a collection that doesn't allow duplicates
Oh really, can the hash itself be referenced?
wdym by "the hash itself"?
I am assuming when an object is added and it creates a hash for the object, then when another is attempted to be added it references the tables hash before allowing it. So I was wondering about how it checks.
Oh sorry somehow I copied the wrong version in https://hatebin.com/ccpkyerkpb
It uses the Equals and HashCode methods from the Edge struct
ok, that makes more sense haha
It check by using the .Equals() function. you can override this in your own class to compare member values.
Can anyone help, when I play with one player it works perfectly, it spawns one zombie and waits until it's dead. But When I play with two or more , the wave system just skips and doesn't check if the zombies are dead. Also instead of only spawning one zombie, it spawns one zombie per player. I'm not sure if the RPC's are done correctly
https://paste.myst.rs/4kfq5k88
a powerful website for storing and sharing text and code snippets. completely free and open source.
broke the cube?! darn it.. whats that doing now?
@clever lagoon count in the bottom left and green edges were not added. I think imma try and swap to the method @leaden ice sent though, so it might not matter.
@clever lagoon @leaden ice Thanks for the help.
cheers!
not ignoring you- RPC stuff is just not my wheelhouse.
hey! been using unity for about 3 weeks now, and I've completed ~12 courses. I'm starting to notice that the courses I'm doing seems to have a lot of variability in the quality of the C# scripts they write, and I'm getting pretty confused about best practices. Is there a wiki or something for this community where I can see a recommended list of courses that teach the correct way to design the gameobjects and scripts? I'm just apprehensive to keep investing 5-10 hours into some more courses that are doing it wrong.
I was looking at the unity.learn stuff, but that seems to be more geared toward complete beginners learning their first software language
i'm more interested in the correct way to go about separation-of-concerns, when to use events vs functions, what to break out into controller/manager, etc.
Yeah I'd start with manager patterns
You got your singletons, your observers, servicelocators
Model View Presenter (MVP)
interesting, I've seen quite a lot of criticism for MVC/MVCS
so this book is the best resource? does the comminity have a wiki/FAQ or something with courses? I'm more of a learn-by-building kinda person
object pooling is more specific to game design and usually mandatory so understand that
yeah I haven't really found it useful as much in Unity
it's just not very clear when i should look to using events/subscription stuff, vs when to just pass arguments to a function, etc
the book you linked has MVP as a bullet point
yeah I know
events help you decouple code
yeah i'm looking for an example course/project that uses them the correct way
a lot of the udemy-style courses are from people that don't come from a software engineering background, and are pretty much beginners
no offense to them
the most very basic usecase, think about a ScoreManager. Whenever point goes up you only need 1 event that tells anyone subscribed what to do, eg SoundManager plays a sound, UI Displays score change
imagine having ScoreManager call each method in each script when adding a point
that would be hell
yeah im aware of how the mechanics of these work, but i was hoping to see a complete example showing when to use a specific pattern, and justification for why that design is preferred
Subscription stuff has been helpful for my items system for when I equip some upgrade. For example I have +% to fire damage, so I'd only want my items listening on modifiers of that specific type instead of iterating through all my items and such.
i appreciate all the advice, but I'm specifically looking for resources/courses
this is something that comes more from experience imo you start to see the areas of perfect use
yes i want to find someone with experience explaining the concepts in some formal way (course/book/etc)
so i can learn this from them
there are general practices all over the web , but everything is up to you
imo the Microsoft docs
for instance, in web development you could find a course or blog that talks about why you would use an event broker vs http for a microservices architecture. And they explain why its appropriate and under what circumstances to consider each
im trying to find something from someone reputable in unity
the official unity.learn seems to be more fundamental, like "what is a monobehavior" or "here is what an array is"
ahh
At most learn the singleton pattern and how you'd load and deload from these pattern types, as well as pooling objects and requesting from them
if you want to start somewhere
yeah this ebook seems to be officially from unity
so i'm kinda leaning toward this being the best there is
unless for some reason they would release a junk ebook
but that seems unlikely
am i making a mistake by reading a 2021 LTS book? (new to the whole unity thing)
Unity and Microsoft, those are literally the sources of everything involved here
ahh
so yeah their stuff is legit lol
honestly i wanted to just start with ECS, since that seems like where the engine is going, but they removed all their official courses on DOTS/ECS from the website
like you cannot access them
not sure why
ECS does seem fun, I was doing a little bit of it but yeah that's a whole different basket of concepts
yeah mainly docs for ECS rn not many resources on it
well the nice part for beginner is that is makes all your decisions for you (or that's my ignorant undestanding)
it looks like it forces you to separate your behaviors in some standard way
can't say that's beginner but more preventing you from digging yourself a *hole with oop
maybe they did all the official courses in pre-1.1 and it isn't compatible 🤷🏻♂️
this is what i'm trying to prevent, yeah
yeah samples are pretty good
do you have resources on an appropriate use of events?
like a good example of using them correctly
have you actually started using them at all?
cause thats the only way it starts to make sense
Do you not understand the concepts of Events?
yes
then the context is irrelevant
not to me
if you understand the concepts why is context relevant?
it's like saying I can implement events in JS but I cannot do the same thing in C#, that's just nonesense
that's like asking if you understand databases, then telling a developer that it's not necessary to understand what data to persist in a database, and when.
knowing how to use a tool is different than knowing when to use it.
not at all
maybe that's not the way you learn
i'm not asking what's best for you.
i'm asking a directed question about resources
it's fine if you don't think that's something you would personally benefit from
everyone is different
what I'm trying to get across to you is you seem to be holding yourself back unnecessarily
ok well i'm possibly not explaining myself well
i'm coming from the software world, but not the game dev world. I've gone through the process of learning from a bunch of courses, and I understand the concepts they are using. However, the people who are teaching these courses are kind of YOLOing the whol design, which isn't something I'm interested in doing. There are people and companies out there that have standards and reasoning behind how to design things properly. I am seeking this information.
don't crosspost
@rigid island this unity resources page is nice. It's got all kinds of stuff.
they got lots pdfs yea
i see, all the MVP/MVC stuff is specifically for the 2D UI (in the book)
the udemy course I took was trying to kind of jam MVC into everything through some framework in the asset store
wtf you can open PDF ebooks in MS Edge and it copilot can read the ebook and you can ask it questions.
this is new to me, pretty neat.
it understands the book and is responding to questions about it
why would you want to do that
it can elaborate on concepts
So can reading
If I find an AI has written something I immediately doubt its credibility and go look for other sources. It's a mystery to me why people would go directly to it
everyone learns differently.
if you know enough to not get fooled by hallucinations, it's great
i use it at work and it's improved some of my stuff before
sometimes it just lies though
@rigid island turns out that guy that wrote the official unity ebook you linked has a course on udemy. Nice! thanks for the link.
but if you knew enough to not get fooled by hallucinations you wouldn't need to be asking it anything
it's given me refactoring ideas that are seriously impressive on occasion
like it understands advanced concepts like monad transformers
https://hatebin.com/hiinkrawqw
Some snippets of my event stuff if interested. Basically it replaces iterating my items for stat changes so not much of a difference there, but in this example I also check if the ability can use trigger modifications, so instead of iterating all my items to check every time, I only subscribe once when creating the ability.
well, it's an ability and mod system. Mods affect abilities, and to do that usually you need to update every ability when you acquire a new mod.
The vanilla way is just iterate through all your abilities which is fine, but when it comes to cases where you should already know that some abilities can't use certain features, then there's no reason to iterate over them.
so you have a class nested in a class, that subscribed to this event at the top-level (not in a Start function or anything)?
modHandler.UpdateAbilitiesStatsEvent += UpdateAbilityStats;
These are just c# classes, so I can use the constructor here for that.
otherwise for monos, yeah either Start() or an Init() method you call yourself
small typo on :61
lol, well it was chopped up from a bunch of more code
but otherwise looks fine for the basic idea of it all
yeah so this is a good example here where i would have a question in the courses I'm taking. Specifically look at line :67
in the courses, they will have a class param, declared at the top, and then "abuse" functions that take no arguments. They just pull from the params.
so, you get a new mod, all items with stats (which is all of them here) will update themselves accordingly, but if the mod is a trigger mod, only those with trigger capabilities will update.
whereas I'm much more used to line :67, where it just takes the value as a parameter to the function
and they never explain why they chose one or the other
can probably cut down on the stats idea too and only have some items subscribe to specific stats. Just some ideas
i don't understand why you'd ever not do what you're doing here on 67
it's way less brittle
oh yeah always use bitwise enums if possible
no i mean just a function with an input
as opposed to declaring mods top-level and referencing it on 87
ah, yeah I see what you mean
i just keep seeing that pattern all over the place, even in paid courses
honestly I havent read crap, I just been playing with ideas
that was kind of the root of my original question in here. Nobody in these tutorials or courses seems to explain why they choose to write things the way they do
there's actually a few problems with c# events too and that they do create garbage
for instance, you can now unit test your protected bool CheckAbilityRequirements(AbilityFlags modAbilityFlags) if you choose
object-oriented code stores mutable state in objects that can act on that state with methods
because you can pass it test values
it's much more common to see that
whereas the class-level implementation of this would be a PITA
I've been advised to try to stick to unity events for heavier subscription systems
such as enemy targeting systems
where you're constantly subscribing on and off
yeah the only downside of events (in my naive understanding) is the same downside as actor-systems in languages like Scala. They are harder to ctrl+click and debug in your IDE
yes (precisely because they let you decouple things)
you cant really follow their use-path without using the find-all
rather than in functional languages, where you usually just write functions that produce new data from existing data
but for this, I'm not really sure why many games/classes/etc seem allergic to the parameter declarations on functions
it's like they are unaware that you can use them
agree
so where in that file are you seeing this problem, exactly?
no i was saying that @latent latch implementation makes more sense to me
he has a function that only cares about the AbilityFlags , it literally nows nothing about what else is on mod
it's a pretty clean idea. The goal here overall is to reduce as much iterating as possible
so it's appropriate IMO that this should take only what it needs and should do so via an input param
Both events and bitwise operations do remove a lot of it
whereas i'm commonly seeming people just reference mod inside a function that takes no inputs
it prevents you from encountering a bug, then saying to yourself "okay who is using mod 🤔 " and then getting annoyed tracking down all of its mutators
that would make sense if there was a single mod field in your class
rather than grabbing the flags from the mod field and passing them to the method
one would wonder why that method is even attached to your class if it's not going to use the data from the class
ok well a good example is 95
protected AddAbilityStatMod(AbilityStatMod mod)
{
AbilityStatMod.Add(mod);
}
this function cares about mod, and i know this by looking at the function signature
as opposed to just abusing () all over and tracking down all of your references inside the body of those functions
i'm not sure how you could coherently write a function that adds a stat mod without a stat mod parameter
I would be annoyed if I had a method that took a bunch of parameters that turned out to just be fields from my class
where does mod come from on line 45?
public class Foo {
private int bar;
private GameObject baz;
private Transform buz;
public void Something() {
DoThings(bar, baz, buz);
}
private void DoThings(int bar, GameObject baz, Transform buz) {
// ...
}
}
this would not make any sense to me
unless, of course, DoThings could be meaningfully called with different values
i dont see the original reference to mod, maybe im blind?
seems like a typo from line 43, since mods is the wrong word for a single AbilityStatMod
The abilities preload mods already in the modhandler when created
im typing this all in notepad++
so 45 is supposed to be mods?
yeah I see some typos
oh, I'm just using notepad++ just to ignore the ide warnings of simplifying names and such
trying to simplify code to show it to someone usually just makes it harder to understand :p
code usually exists for a reason..
public abstract class BaseAbility<SO> : Storable<SO>, IBaseAbility<SO> where SO : IBaseAbilitySO
Well, that's the prototype of the class
along with some covariance interface
public interface IBaseAbility<out SO> : IStorable<SO> where SO : IBaseAbilitySO```
I should start commenting more cause im looking at this like where the heck did I leave off
im not familiar with the type parameterization. what does <out SO> do here?
oh so C# has a kind system?
I gotta run into the problem why I use it again to explain it
that looks like a higher kinded type
but coupling classes by a data class constraint creates problems for me
Covariance and contravariance allow you to use more or less derived types
Covariance means that you can return something more specific than your generic type requires
And contravariance means that you can accept something less specific
what it allows me to do is keep the scriptable object variable declaration as the exact type that it's coupling with instead of a upcasted version
So your interface that demands you to return Parent can be satisfied by a class that actually returns Child
after all, you can freely reinterpret Child as Parent to satisfy the interface
i just learned about this from that book
[RequireComponent(typeof(PlayerAudio), typeof(PlayerInput),
typeof(PlayerMovement))]
but then, if you use the type directly, you can get a more specific type returned
(this being unrelated to variance, just thought it was neat)
You'd probably run into a similar problem if you designed a hotbar that can include multiple different types.
ok here (from book) is another example of a scenario where i am a little confused
[RequireComponent(typeof(PlayerAudio), typeof(PlayerInput),
typeof(PlayerMovement))]
public class Player : MonoBehaviour
{
[SerializeField] private PlayerAudio playerAudio;
[SerializeField] private PlayerInput playerInput;
[SerializeField] private PlayerMovement playerMovement;
private void Start()
{
playerAudio = GetComponent<PlayerAudio>();
playerInput = GetComponent<PlayerInput>();
playerMovement = GetComponent<PlayerMovement>();
}
}
public class PlayerAudio : MonoBehaviour
{
…
}
public class PlayerInput : MonoBehaviour
{
…
}
public class PlayerMovement : MonoBehaviour
{
…
}
he expresses movement, input, and audio as classes. Why not using separate scripts called PlayerAudio, PlayerController, etc?
why one over the other?
this is the kind of stuff that (at my beginner level) is confusing to me
or maybe that's what's being represented with this single file
scripts ARE classes
yeah you're right
And under no circumstances would you put all those in one file
that's probably just shown that way for convenience
they'd each have their own file
you shold see the courses i've taken
they are just jamming shit all over
im learning hard way
learning from experience is better
it wouldnt even compile properly
the guy that wrote this "official" unity ebook that was recommended on here has a course
that @rigid island linked
it hasnt been updated in 4 years, though
just cause they wrote a unity pdf doesn't mean their courses are any good 🤷♂️
i'm assuming that unity vetted this ebook before they put their golden stamp on it
if not, then i'm wasting my time reading it
just saying the ebook isnt a voucher for the course quality 🤷♂️
right, makes sense
which one wrote it, I dont have link
he made some courses and he's got some instructional business called GameAcademy I guess
then he got consulted to write that book apparently
not just because it's ugly
unity is looking for a single class in each script asset
Monos need to be in their own classes, and Scriptable Objects for that matter because this would be ambigious to the Editor without some other support.
Hello! How would i instantiate a gameobject at the location where a SphereCast hit a collider?
What does this part mean or do? where T : BTNodeBase, new()
Unity doesn't actually care about exactly what class a component is made from. It just cares about the script asset.
So you can rename a script asset and change the class name, and all of your components still work.
This is a constraint on the generic type, T
It's listing things that must be true about the type
it's saying that T must derive from BTNodeBase and must have a constructor with zero arguments.
new() is useful if you want to be able to construct instances of T
ahhh ok
without that, there's no way you could prove to the compiler that T can always be constructed
T : BTNodeBase, new()
so everything after T is the conditions required. What if the conditions are not met? Will it throw and error in unity or just return and do nothing?
just grab the point from the RaycastHit struct you get back and instantiate at that spot
you will get a compile error
ahh
if you do Add<int>("hi") for example, it will be a compile error
does this also work with spherecast?
RaycastHit is for spherecast too
Of course.
i see so its mainly there for debugging as well to make it easier
that seems like an odd constraint to only be from a constructor with no arguments. I assume this would be more used with defined argument types?
It's there to make your code make sense and to have the compiler not compile code that doesn't make sense
ahh
Without new(), it would be impossible to ever write a class that constructs an instance of T
i litteraly have the speed set to 1e+16.... it should be faster but no matter how high i make the speed the clones dont follow the player faster. https://hatebin.com/gdcwhqylja
because the compiler could not be convinced that you can do that
You can't do new T() unless that's defined on the class. Or rather, if you defined any other constructors on it, it won't be able to be constructed without params anymore. It's quite useful.
good to know
ill probably want to look into that since first time seeing it
did you update all three clones?
I wonder if you have three clones right now.
(one would then be stuck under the player, moving at incredible speed)
the two black circles are clones. They are prefabs, I edited the speed in the prefab
Check that the instances actually have the correct speed value
if they exist in the scene, they could have had an override set for that field
Yep - show the inspector of one of the instances at runtime
your right, in the scene the speed is diffrent
it's also unclear how targetposition is being set
how do i change that orrivade?
what do you mean?
stop running
show them in edit mode
if they're not there in edit mode then you have some other code setting it
I'd like to use a line renderer to write the title of my game in cursive on my game's title screen. Is there a way to do this without having to input every position manually?
Could do it quick by writing a script to just record some mouse positions and then use those values. Just need to record once
You'll need a line renderer per letter though or itll be one continuous line
I'm picturing a single line. Thanks. So maybe make a script to draw a line renderer and I can save that as a game object while the editor is playing?
You can either have it run during editor, or just do it in play mode and copy the values from the inspector
Doesnt really matter since you're just gonna do it a few times and be done forever
Didn't realize there's a different between running in editor and play mode but irrelevant. I'll give that a shot, thanks
Main difference would be that your editor mode stuff would save its changes, so you would want to add undo. Play mode would just be ever so lightly faster to setup
I' trying to find the file that is the current game log (if that exists) so that if a user submits a bug report, I send that log file. Do you guys know how to find that
My project uses some google apis that use Newtonsoft.Json There isnt any problem with this in the editor or when compiled for pc. However I get console errors when I use WebGL. to get around this I have turned code striping to minimum in the player settings. now I don't get console errors but the code does not run as intended> When I run a function that uses newtonsoft.json the webpage freezes. Any suggestions?
you check the dev console to see if it spits out any errors?
Yeah. right before I make the api call I print out a "here" and that is the last thing that happens before the freeze
well then you probably need to provide more context 🤷♂️
here is what happens in andout of the editor
public void Login()
{
Debug.Log("here");
IList<object> names = GetColumnValues(sheetsService, spreadsheetId, "Sheet1", "A");
int row = names.IndexOf(usernameInput.text) + 1;
string correctPassword = GetCellValue(sheetsService, spreadsheetId, $"B{row}");
passwordEncrypted = GetHashString(Password.text);
Debug.Log(correctPassword);
USER.Instance.username = usernameInput.text;
USER.Instance.row = row;
USER.Instance.highscore = Int32.Parse(GetCellValue(sheetsService, spreadsheetId, $"C{row}"));
USER.Instance.runs = Int32.Parse(GetCellValue(sheetsService, spreadsheetId, $"D{row}"));
USER.Instance.skins = GetCellValue(sheetsService, spreadsheetId, $"E{row}");
SceneManager.LoadScene("home");
}
this is the function that gets called when login is pressed
What's GetColumnValues/ GetCellValue methods?
private static IList<object> GetColumnValues(SheetsService sheetsService, string spreadsheetId, string sheetName, string columnName)
{
// Define the range for the specified column
string range = $"{sheetName}!{columnName}:{columnName}";
// Make the request to get values
SpreadsheetsResource.ValuesResource.GetRequest request =
sheetsService.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange response = request.Execute();
IList<IList<object>> values = response.Values;
if (values != null && values.Count > 0)
{
IList<object> columnValues = values.Select(row => row.Count > 0 ? row[0] : null).ToList();
return columnValues;
}
else
{
return new List<object>();
}
}
private static string GetCellValue(SheetsService sheetsService, string spreadsheetId, string range)
{
// Make the request to get the value of the single cell
SpreadsheetsResource.ValuesResource.GetRequest request =
sheetsService.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange response = request.Execute();
IList<IList<object>> values = response.Values;
if (values != null && values.Count > 0 && values[0].Count > 0)
{
return values[0][0].ToString();
}
else
{
return null;
}
}
What's SpreadsheetsResource.ValuesResource.GetRequest? What does it do?
As well as the Get method.
What does request.Execute do?
I believe the get method forms a http request that includes some authorization info and the request.Execute preforms this
Make sure it's compatible with WebGL. WebGL doesn't support threading as well as file system access. I think some web request implementations are also limited.
I'd imagine that it uses threads, which is why it fails.
ugh why must so many data base options not work with webGl
Because it's literally running in the browser, that imposes many restrictions on the app.
Your best bet would be using web API for the google spreadsheets and not the dot net client.
I tried that but couldnt figure out how to incorprate the authentication
I might just make a seperate database and host it locally
Wdym locally?
yo
say i have a List of lists with [ [1,2,3,4,],[7,8,9] ]
and i want to add a list [1,2,3,4,5] to it but i want to detect overlaps and add to it so that the resulting list of lists will be:
[ [1,2,3,4,5],[7,8,9] ] (as apposed to [ [1,2,3,4,],[7,8,9],[1,2,3,4,5] ])
more directly what I'm trying to do is... I'm making a match 3 game where you can move pieces after youve already made a match but whenever i add a new element to a existing set of matched elements, it basically resubmits the whole group of matched elements to the list of existing matches leading to duplicates and trouble finding out how many separate matches were actually made... and I'm trying to fix that
How would you know wether to add the 5 to the first or the second sub list?
knowing c#, there's probably a single method made for this lol
but I'd just keep everything sorted, then forloop after finding the first element in each list
If you know that the 1,2,3,4,5 sequence is associated with the 1,2,3,4 sequence, you can just overwrite it then. I don't k ow the whole context so It's hard to say how feasible it is.
oh yeah, I guess another requirement is where that 5 should go, but it seems that we'd just add it to the first list it can be inserted into
What would a list of lists like this become:
[1,3,4][2,5,8][5,7]
Is there a list of what WebGL doesn’t support and maybe a way to test the game in WebGL? I’m writing a really simple one and I want to test it for myself
I’ve never put anything on itch.io
but yeah, sort each individual list first, then sort the list of lists by the first element and from there it would be some iterating
There is in the manual. Look it up. I don't have the link on me.
As for testing, you can just build a WebGL build and test locally.
Longest common subsequence
Sorry for getting back late something came up so I was distracted for a bit... I figured it out tho
public void AddResultWithOverlap(MatchResult newResult)
{
// Check for overlaps
var overlappingResult = presentMatches.FirstOrDefault(result => newResult.allMatches.Intersect(result.allMatches).Any());
if (overlappingResult != null)
{
// If overlap exists, update the existing result with the union of the two results
overlappingResult.vertMatches = overlappingResult.vertMatches.Union(newResult.vertMatches).ToList();
overlappingResult.horzMatches = overlappingResult.horzMatches.Union(newResult.horzMatches).ToList();
}
else
{
// If no overlap, add the new result to the list of results
presentMatches.Add(newResult);
}
}
I'm not literally working with ints and in my case that isn't possible as all lists are made of sequential elements
If duplicate values not allowed then why not just store them on single list and have an additional int for the actual list they are
I really can't imagine a situation in a game where you would need to find overlapping number sequences in a raw fashion like that. I'm sure there must be some more context that you could use. For example, give your match results an id and update them by id.
You're not writing an accountant software. You don't need to make your life harder on purpose.
I wanted to make the system modular and usable for basically whatever I need to, so I have a system where I have a List of all existing matches on the board each match being stored as a "match result" which contains a 2 lists of its horizontal and vertical matches each which are stored as a references to each one of the elements in that match
I don't see how adding a generic identifier makes it less generic/modular.
Also, making modular systems is great, but don't make it the sole purpose sacrificing everything else(performance, readability, development time)
If lists could only be a certain size I would personally make specialized structs to compare without allocating all these lists and stuff; but it's very specific to the game and familiarity with the type of approach. I personally find the idea of having so many hashsets and lists a bit of a nightmare idea
building to PC just fucked everything over idk why
none of my enemies move
my hitbox doesn't work
my dialogue doesn't run
any idea why that coudl be?
Bugs
Can anyone help me with this? I want to wrap my player character around the screen edges. When he hits the left side of the screen, I want him to appear on the right side in the same vertical position. My scene is set up so that the player only moves in the x and z planes, and the camera is tilted 45 degrees on the x-axis. But my code can only transfer player character to the center of the screen.
I'm not sure what you mean by identifier, that wouldn't really help?
take what i do in this video
before that would of been considered 2 matches becuase the first match of the 4 orange elements and then it subjects a second containing all 5
Ok, that's vastly different from what I've imagined. I thought you were talking about game matches or their results.😅
That's why context to your question matters.
any idea what I could check to make it work?
Debug.
Oh lol no I'm talking about the matching of elements in the game
Why not just recalculate everything every time a piece is moved?
in my initaly question i said that more directly what I'm trying to do is... I'm making a match 3 game where you can move pieces after youve already made a match but whenever i add a new element to a existing set of matched elements, it basically resubmits the whole group of matched elements to the list of existing matches leading to duplicates and trouble finding out how many separate matches were actually made... and I'm trying to fix that
I would probably using intervals on each x and y then just binary search through the interval for each change, merge or split
Yeah,I guess I should've paid attention to the "I'm making a match 3 game". At first it sounded like gibberish to me, but now I remember that there's a game like that similar to what you have in the video.
I mean like, everything works on the editor, but not when built
that felt inefficient but i know needless optimization is bad
Debug the build.
literally candy crush or bejeweled or puzzle quest(what the system im making is inspired by(
There are more and better ways to optimize it if you really need to. For starters implement it as simple as you can.
If you have pattern eg AAABBCCBD
Then having intervals [1,3][4,5][6,7][8,8][9,9]
You can attach the debugger to a build as well as the unity console/profiler. Check the debug section:
#💻┃code-beginner message
how to stop rigid body player from bouncing when moving on slopes?
Dont use a rigid body
dayum
Rigidbody player controllers are just bad. People use them because for some reason tutorials are almost always with them. But always at some point you hit a case where you want your player to move in a non physics correct way and that is hard to achieve with a rigidbody.
Most games out there use some form of a kinematic character controller
I don't see a problem with using an rb. You can do all the same + rely on unity physics when needed.
Find the cause and eliminate it.
I've had to deal with a few kinematic controller assets, and I must say they have their own problems, so it's not as simple as just not using an rb.
im trying to use StringBuilder in Unity which is being used in this guide but it doesnt seem to be there
nvmi found out why, i had to use System.Text not System
Make sure that your !IDE is configured so that it will let you use the quick actions to add the correct using directives
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
hi, is there a reason why my one way platforms aren't working?
i can't jump through from the bottom
Still not code related. #🖼️┃2d-tools
sorry my bad
Hiii is there an easy way to remove all delegate listeners or do I have to manually remove them all? ^^
Or can I at least just set the delegate thing to like null or something
If it is a normal delegate then just assign null. If it is a UnityEvent then call RemoveAllListeners on it
thanks!
I didn't know you could do that all the answers I got when I looked it up were not straightforward at all lamo
In Unity what is the name of a function/method/event that can be triggered and you can subscribe to
In UE its called Event Dispatchers if this can help
Maybe UnityEvent?
Well its a way of doing it, but unityevent are global, not per instance
sorry you are right, this is what I needed
i rechecked the doc
Cool! ^^
ty
yw!
Under the hood it's just a static/global access multicast delegate. You can have an event/delegate as a static member in C# as well.
Nevermind, thought you were talking about FCoreDelegate events.
hey guys! To the peeps who've used timelines before, how performance friendly is it? I'm halfway into making a custom track for it that takes in dialogue so I can give story segments in game some life-- but it just dawned on me that maybe having all these clips might have us run into performance issues. For context, we're hoping to have this run on mobile/school laptops.
I'm not pressed if I have to rethink how I'm handling this, but I'd like to at least know if it's worth it continuing with the timeline idea ^^,
timeline itself is just a bunch of keyframes that are lerped over curve values
so that's probably very miniscule, so if there are performance problems then it would be more related to the assets that you may be using such as audio
ty for the extra details, I am not used to static class stuff xD
what im saying is you'd run quicker into having too many assets loaded in than a bunch of keyframes from your timelines
okay so if I just don't go overboard with what I'm manipulating then we'd probably be alright?
you're not likely to run into any problems faster with the animator than without
gotchaaa then i surge on. thanks!
hello there, I spent some time trying to figure out what is going on, but I couldn't find any answers. I am playing a little with standalone Unity tests. And no matter what I do I can't load my custom scene to the game. Does anyone had similar issue? FYI: in editor everything works fine. Maybe loading custom scenes inside standalone build tests it's not supported?
what do you mean by "custom scene"?
I mean my gameplay scene, created and saved inside Unity editor.
