#archived-code-general
1 messages · Page 239 of 1
nahh looks fine
ok do you know what the issue is this is really bizarre
is the Log printing the value correctly?
try also printing the end result like movementVelocity
that works as intended except no z value
you are using Vector2 rather than Vector3
yikes
V3clampmagnitude
well no I have to make it stay inside a placing area
thats even easier
I'm making a 3D version of the watermelon games except instead of fruit it's gonna be my classmates faces
how so?
wdym its simple stuff lol just doing some simple < > checks
yea but I don't know how to properly acsess the transform values
rb.position
my favorite thing is going "well that didn't fing work" after every fail because it lessens the pain with a laugh
Hoping this is a good place to ask this, but is it possible to add a white tint to a sprite? Kind of like how you can tint a sprite with the unity sprite renderer, but since the rgb values there are by deafult at 255, and also capped at this, I can't make the sprite anymore "white". Not looking for a full solid white, just a tint.
like what a flashing effect?
Unity Asset Store BLACK FRIDAY Sale - EVERYTHING on this page is 70% off:
https://assetstore.unity.com/?flashdeals=true&aid=1100lwgBQ
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this project's Source Files + Code) - https://www.patreon.com/sasquat...
Yea, most resources I could find had the flash be full opacitiy which wasn't what I was looking for, this seems to have control over that value however. Thanks!
await AuthenticationService.Instance.SignInWithUnityAsync(accessToken);
What the hell is the access token??
did you peep my vid?
i was gonna do username/password authentication but im too lazysooo kekw
the access token is there when user was signed in via browser uri
i ahvent signed in before tho
hence the subscription to the Signed in event
watch the whole vid if you're doing Unity player accounts, i go through it pretty much in less than 10 min
ok
btw i recommend either using ur own voice or not having any voice at all
the robot voice is very anoyying
and i notice the mic is unmuted
next vid coming up it uses this + the Code link which is signing the same account on another device using a code only
Yeah I'm away from my regular setup so ican't record voice for a while lol
This surprisingly crashes my game
Which approach would you use to draw these arrows dynamically at runtime? (ie. in the example, they represent physics forces and animate on FixedUpdate())
maybe a line renderer but that prob wouldn't explain the arrows at the tips
Hi, I'm facing a very weird issue. I have no idea how to fix it.
[DELETED]
↑ this is a dumb script I wrote
Whenever I add it to a normal (empty) GameObject in the scene, then, as soon as I try playing from the editor, my object becomes permanently infected with a RectTransform thereafter, replacing its regular Transform component.
this then stays that way when I stop playing and get back to the Editor (I believe one warning appeared when entering Play Mode, the other one when exiting~)
Why does that happen and how can I prevent a RectTransform replacing my Transform, for objects equipped with this script?
Using version 2021.3.9, by the way!
Do not hesitate to ping me if you've got any clues ^^
Also, googling did not help me much, I only encountered the one person seemingly using a Mask, or whatever UI thing it was, in their script, thus tricking Unity into believe that this object was meant for a UI canvas. If that's the case here… I can't see it? Where would the problematic object be in there?
aaaand now the issue just won't happen again -_-
fixed I guess! ^w^
but yeah weird, no idea what causes it
Can someone help me with my unity 2d project? I cannot seem to make it that whenever the sprite goes left and right they start the walking animation.
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
public Animator anim;
public Rigidbody2D myRB;
private SpriteRenderer spriteRenderer;
[SerializeField] public float speed;
private void Start()
{
anim = GetComponent<Animator>();
myRB = GetComponent<Rigidbody2D>();
spriteRenderer = GetComponent<SpriteRenderer>();
}
private void Update()
{
myRB.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")) * speed * Time.deltaTime;
spriteRenderer.flipX = myRB.velocity.x > 0f;
}
}`
If you want to see my ingame unity settings lmk
You are not calling any animations in that code?
yeah i dont know how to haha
Ive set the animations up in the animator, adding conditions. I have no clue what to do from there..
in your Update() method:
anim.SetBool("isRunning", myRB.velocity.magnitude > 1);
Can u explain the code for me. So im not just putting in code that idk. I actuallt kmow so i can do this for next time
anim.SetBool(). Sets a bool condition on the animator to whatever value you put in as the second parameter.
'myRb.velicity.magnitude' is the "length" of your velocity, i.e. 0 when there is no movement and higher than 0 when there is. Basically how fast it is going. by writing
(myRb.velocity.magnitude > 1) we create a bool that is true when the magnitude value is greater than 1 and false if it is lower.
So the code is: Set the bool condition on this animator named "isRunning" to true if the RB has some velocity, and to false if it doesn't.
Thank you so much 🙏
Also one last thing, When my animations plays, the animation is goes small, even though the pixel per unit are the same??
Got a question about a dont destroy on load gameobject
maybe the sprite itself is smaller?
It cant be that much smaller. Ill have a look ty
So currently I have this scene that has a UI button gameobject that has an OnClick function tied to enother gameobject. The problem is that that other gameobject has the Dont DestroyOnLoad and if there is a duplicate itll destroy the copy, this means that the UI button's OnClick function wont work cuz the other gameobject is missing. How do I reassign the other gameobject to the ui function?
How do i check the size of sprites
find them with the windows file explorer and rightclick properties
Alright ty
Can anyone help me with this?
I made a script so that my player is teleported to a certain position if they fall off. But the camera keeps bugging out and seems to try to follow etc, but I just want it to snap back with him
I'll be honest, you shouldn't be connecting ui elements to a ddol object/singleton. You should be thinking of another object oriented way to go about what you are doing.
But if you must do what you want, you need to attach a script to your button and set a static class reference to it so it's easily accessible, Instead of using game object find. Regardless of how you end up finding the button again, you just need to call remove all listeners on the button and then add the on click listener to point back to your function.
I found a temporary solution rn but can u elaborate more on how to do OOP in this regard
Im still new with how OOP works
Do you need to see them in game, or just for debugging/editor?
Drawing 2 meshes per arrow is what I would probably do (the line itself, scaled along its length, and the end of the arrow itself)
In short, "most" ddol's are used as managers/singletons for utility classes, persistence session game state, etc. Or when the ddol object script relies on itself or its children only. It shouldn't have relation to any objects not within itself when moving scenes so it doesn't lose references.
I'm not saying you can't do what your doing and it be fine.
whats ddol again?
DontDestroyOnLoad I'm guessing?
oh right ok
So what ur saying is that ddol objects must be independent from any other element aside from their own children?
I've never had issues with VS code not responding and not it is completely broken what should I do
"Must be" , no. But I would stay away from the situation you got yourself into which is losing reference when that object is destroyed. So many use cases for why you would use ddol objects but I would say what you are doing is not one of them.
can't even close unrelated programs but some work like discord/chrome
So then how should I use OOP
As in like
When should I use it
Did you install a new extension? Try uninstalling your extensions and reinstalling only the unity/c# extensions
Sometimes I hit a break point and forget I have debugger mode on, makes everything feel broken like that.
Well everything you do in unity is object oriented I would say. You should have that design thinking the entire time.
Hey all, we installed HDRP recently and we're getting this error:
Can I load the same scene additively many times via code ?
Is it better to create an interface or to write a class for Interactables?
I've seen programmers use both designs
Have seen player holding this board in game, its toggles there is animation how its being made,
Is it just simple animation of gameobject or something else?
And also how paper on text fits well with the Game object any help?
the text on the gameobject should be a simple World Space canvas and the animation on the toggles should be an animation of the checkmark sprite
might be a dump question to ask haha can we add multiple canvas like one for Overlay and one for World Space
The problem with interfaces is that they don't allow base implementations and they can't be serialized in the inspector. The problem with base classes is that you can only have one. Which one is better depends on what you need.
ofc. You can also split stuff like resource displays and pause menu up etc.
oh got it Thanks buddy
I wanted to add a few parameters to each interactable, but I don't think that its possible with interfaces
I've made an Interactable class which has a OnInteract UnityEvent and a bool canInteract
and i just inherit it to all my interactable classes
Thanks
You could have a class called 'InteractableData' and pass that as parameter. Then you can either add variables to it or inherit it and create specific data for each interactable, i.e. DoorData. The only problem with that is that you need to cast it to the correct type before you can use it.
But there should never be a reason to get the gameObject in the first place, since NPCScript has a reference to it anyway.
https://docs.unity3d.com/Manual/CustomPackages.html
The custom package documentation is hilariously terrible.
It does an awful job of explaining how to start a custom package and what it looks like to develop one.
For the custom package manifest it doesn't tell you what its supposed to look like; one has to grok 3 pages of documentation to know what it is supposed to be. Even then, there are so many questions you have to read in between the lines for.
It's laughably bad.
I actually made a package that auto generates the package structure in your assets folder:
https://github.com/Gruhlum/PackageGenerator
That makes the joke of the custom package docs even funnier. The community is patching around the awfulness. Thanks for the laugh
how should I go about clamping the Z rotation of my object between e.g. -40 and 40 degrees
this just makes it permanentally stuck at -40
I don't think eulerAngles will ever be negative, they stick to 0-360
oooh right
You might have to subtract 180, then clamp, then add 180 back
there are probably also functions that handle exactly that, but I don't know them
how to get reference to loaded scene other than OnSceneLoaded and GetSceneByName/Index/Path ?
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("Scene2");
while (!asyncLoad.isDone)
{
yield return null;
}
asyncLoad.
can i get reference to scene from asyncLoad ?
i load multiple scenes with the same name so GetSceneBYName doesnt work.
I don't think you can
thats problematic cause i cant pass a param to OnSceneLoaded either
how should I go about clamping the Z
how to get reference to loaded scene
It does an awful job of explaining how
can someone explain to me:
public interface IMyInterface<out T>
I've looked it up at least 4 times, and I never understood it
@polar marten you need to make sure you read and understand messages before you attempt to "answer" to ensure you aren't hallucinating
Do you know what an interface is ?
yes
I just don't understand how the <out T> works vs just normal generic <T>
and vs normal non-generic interface
I have all these rooms generated on Start via procedural generation, is there a way i could bake occlussion stuff post generation?
or would i need to come up with my own occlusion solution for htat?
With an out T you can do the following:
IEnumerable<string> strings = new List<string>();
IEnumerable<object> objects = strings;
You can upcast the interface
This image describes perfectly its behavior
how does this work when writing the interface then?
ok i have a better idea.
Lets pretend that you have:
class Fruit {}
class Banana : Fruit {}
interface ICovariantSkinned<out T> {}
interface ISkinned<T> {}
and the functions
class Program
{
void Peel(ISkinned<Fruit> skinned) { }
void Peel(ICovariantSkinned<Fruit> skinned) { }
}
The function that accepts ICovariantSkinned<Fruit> will be able to accept ICovariantSkinned<Fruit> or ICovariantSkinned<Banana> because ICovariantSkinned<T> is a covariant interface and Banana is a type of Fruit,
the function that accepts ISkinned<Fruit> will only be able to accept ISkinned<Fruit>.
lets pretend that is a function thats outside everything
i updated the example
i have a box trigger and i want it to whenever a player goes inside it, the door opens i made a bit of code to find out the problems with it and to make it work.
if ("Gorilla Rig") is inside of ("OpenTrigger") play anim ("DoorOpen") wait until ("DoorOpen") is finished then play ("DoorIdle)
again this is just simple code that i want to make work, how do i fix it?
could you send the code that you wrote?
i see. so how do I populate the interface differently when it is a Covariant interface?
the whole point of having the generic is to call methods depending on the type, after all
correct
but if you gotta assign the same interface that is of type of a class A to a type B you gotta put the out keyword in front of the generic
class A {}
class B : A{}
interface IMyInterface<out T> {}
IMyInterface<A> foo;
IMyInterface<B> = A; // This will compile since the generic its defined as out T
class A {}
class B : A{}
interface IMyInterface<T> {}
IMyInterface<A> foo;
IMyInterface<B> = A; // Compilation error
you wanna create a C# script that performs that?
yeahj
There are hundreds of tutorials on how to get started, I suggest you check them out first to learn the basics of C#
for checking trigger states of a gameobject you can use methods like OnTriggerEnter, OnTriggerExit and OnTriggerStay
for playing animations you could use an Animator and define some states on an animator layer (the base layer by default)
what?
i dont know what that is tbh
its a visual studio thing i guess
that code will never work cause it's not written in C#
oh
i suggest you to watch some tutorials where they cover Triggers and Animations
You were already told this will never work. Not a single piece of this is valid nor makes sense. If you actually want help, take a lesson first, if you are just trolling (much more likely), just stop
so... how do I put a member into the interface to actually make use of the <out T>
anyone got time to help? :)
public class Enemy { }
public class Boss : Enemy { }
public interface IEnemyProvider<out T>
{
T SpawnEnemy();
}
public class EnemySpawner : IEnemyProvider<Enemy>
{
public Enemy SpawnEnemy()
{
// Implementation to spawn a regular enemy
return new Enemy();
}
}
public class BossSpawner : IEnemyProvider<Boss>
{
public Boss SpawnEnemy()
{
// Implementation to spawn a boss enemy
return new Boss();
}
}
And the implementation:
IEnemyProvider<Enemy> regularEnemyProvider = new EnemySpawner();
Enemy regularEnemy = regularEnemyProvider.SpawnEnemy();
IEnemyProvider<Boss> bossEnemyProvider = new BossSpawner();
Boss bossEnemy = bossEnemyProvider.SpawnEnemy();
that helps. ty
and just to be clear, then you can't use T as the type of an input arg? because there's no way to know?
I use convariance just because the compiler yells at me and I have to comply with it
on that topic, is there a non-dumb way to do this:
if (associatedPrefab.TryGetComponent(out ISimpleAutoTileMono<TilePlacementInstance> mono)) mono.AssertValid();
else Debug.LogError(error_msg");
} else {
if (associatedPrefab.TryGetComponent(out ISimpleAutoTileMono<TilePlacementContiguous> mono)) mono.AssertValid();
else Debug.LogError(error_msg");
}```
where public interface ISimpleAutoTileMono<TTilePlacement> where TTilePlacement : ITilePlacement
I was wondering if I could make it simpler with Covariance, but that interface requires a method where the input is of type TTilePlacement
you could create a method that checks whether its Individual or not
void CheckAndAssertValid<T>() where T : class
{
if (associatedPrefab.TryGetComponent(out ISimpleAutoTileMono<T> mono))
{
mono.AssertValid();
}
else
{
Debug.LogError("error_msg");
}
}
and then
if (autoObjConversion == AutoTileToObjectType.Individual)
{
CheckAndAssertValid<TilePlacementInstance>();
}
else
{
CheckAndAssertValid<TilePlacementContiguous>();
}
that where T : class tells the compiler that it won't accept interfaces types that are not classes
like int, float, bool and so on
I think that would work. Just checking options to avoid all the downcasting.
but I don't think it would work here, which is unfortunate.
So, there seems to be very little documentation about the new navigation package that's why I am asking around: I want to bake a navmesh on runtime but it takes a ridiculous ammount of time and it blocks my main thread, is there any way to move it to another thread? Can it be used with the jobs system? Can it be run asynchronously?
one more interface question. I want an interface to only be attached to Monobehaviours, and I need everything that implements that interface to call the exact same method in OnDestroy. Is there a way for me to do this?
Thank you
No on both counts, as far as I know.
Probably want to use events for that, otherwise do it all in the base class
I am thinking about how to do this.
maybe the interface should force the implementation of a property tied to an event, and then interface method can add something to it?
One option would be to make your own class that subclasses MonoBehaviour
Give it virtual OnDestroy and Awake methods
or maybe interface forces public void OnDestroy, and then interface can add a method to it?
Have the class test if it's an instance of IWhatever and do the needed thing if it is
This feels gross
well, only a little gross
protected virtual OnDestroy() {
if (this is IWhatever interfaceInstance) {
interfaceInstance.Cleanup();
}
}
now you just need to make sure you call the base method if you override the virtual method
It is a generic interface, so it can't be put on a gameobject normally
must be made concrete
changing to a monobehaviour doesn't change that
idk. maybe is there any way for an interface to force a class that implements it to call specific code?
public void PlayerRot(float rotDirection)
{
Quaternion targetRot = Quaternion.Euler(0f, transform.rotation.eulerAngles.y + rotSpeed * rotDirection, 0f);
transform.rotation = Quaternion.Slerp(Quaternion.Euler(0f, transform.rotation.eulerAngles.y, -transform.rotation.eulerAngles.y), targetRot, rotSpeed * Time.fixedDeltaTime);
isRotating = true;
timer = 2;
StartCoroutine(ResetRotationFlag());
}
anyone got any idea as to whats causing the rotation to continue where it left off before resetting to 0?
Possible workaround:
public class DestroyDetector : MonoBehaviour {
public event Action DoOnDestroy;
public void OnDestroy() => DoOnDestroy?.Invoke();
}
///// <summary>Remove self from entity ledger. </summary>
private void LogDestroyedObj() => EntityLedger.GetInstance()?.LogDestroyedEntity(gameObject, EntityLedgerCategory.Tile);```
too dumb?
feels wasteful to make a whole monobehaviour like this
Maybe default interface implementation can help you here, if you are on the newer C# version?
I believe I am as far as unity allows
Maybe a default OnDestroy method in the interface?
Havent used those myself, just throwing some ideas
I'm not exactly sure how unity works with that tbh
I might make it an abstract generic class, but I feel like that might restrict my ability to make classes, since we can only inherit once
fuck it. I'll just make an abstract class
I might be remembering wrong but the default interface methods would probably just cause your regular OnDestroy methods to not run at all. I say abstract class is exactly what you want here
I'm just going to go with my standard pattern:
public abstract class SimpleAutoTileMono<TTilePlacement> : SimpleAutoTileMono where TTilePlacement : ITilePlacement {}
public abstract class SimpleAutoTileMono : MonoBehaviour {}
the latter class just being a convenient way to access the non-generic methods
I have a box that I want to move to my variable called mousePos (mouse position but kept within distance from the player). Using transform.position = mousePos works well except that it doesn't take in account other colliders. So I'm trying to use RigidBody2D.MovePosition(mousePos) but for some reason the box only moves on the y axis and not on the x... I have no idea why this isn't working as transform.position = mousePos does work and I'm not changing any code (except for the line where I move the box ofcourse) when I'm using MovePosition instead. Is this a common issue? Is there a better way to take in account other objects?
move position is supposed to be used on kinematic rb's so it'll ignore the collisions anyways if you do that. As for why it doesnt move on the x axis, that's probably an issue in the scene rather than in code, or mousePos isnt what you thought it is. MovePosition is meant to be used on kinematic rb's (meaning it'd ignore colliders anyways) and with small distances
What other way is there to do this then?
depends on what this is really for, either use non-kinematic rigidbody with addForce/velocity or move the transform but use physics casts to make sure nothing is in the way.
In your current setup, did you debug what mousePos is? I assume something was colliding with your object which is why it couldnt move on the X axis
mousePos is what I want it to be, a Vector2 "clamped" in a circle around the player. Nothing is colliding with the object, it just refuses to move on the x when using MovePosition. I'm assuming that isn't the way to do it then, but I'm also not sure if using velocities is a good idea. Because I want my object to just be at the mousePos rather than going there if that makes sense.
It's possible that move position wasnt working because of frictions or it colliding with objects. Given what you describe, maybe just shapecast from the player to the mousePos and move the object to wherever it hits.
I'll try it out tomorrow
Hey guys, I have noticed unity does not seem to execute the Awake function in abstract classes - But I am pretty sure it used to do that in older versions.
I have an abstract class that handles some backbone of my management stuff and I need the awake method to be executed.
Do I need to find a workaround and if so what could that look like?
Weird. Awake should be executed on all classes deriving from MonoBehaviour. So if you have an abstract class that derives from MonoBehaviour, then create a child class that derives from the abstract class, Awake should be executed assuming you've implemented it in the child class. What's going on?
But does it need to be in a child class that is not abstract for it to be executed?
Because what I have is an abstract class Manager containing a static reference to itself
public abstract class Manager : MonoBehaviour
{
public static Manager Instance;
private void Awake()
{
if (Instance != null)
{
throw new ArgumentException();
}
Instance = this;
}
And in my thinking declaring this static instance of the manager would then force it to initialize the script, because now we have a static Manager that can be accessed from everywhere. But this Awake method is never called
awake should be called
How would it, the script isnt running because you cannot make an instance of it
Oh, it's abstract so yeah you need to derive an actual class you can create an instance of
But I'd really like to have this static Instance field so that anywhere in the project I can go
Manager.Instance.DoMagic();
Because then the actual management stuff can go in regular MonoBehaviours that sit somewhere in the scene. The Manager.Instance just handles handing out references to scripts that need them. This way I dont have to hardwire all the references or have all the management classes be static. But I see the error in my thinking now and will retry something else.
Ahhhh I am such a dud 🤣
Ofc, I am always only thinking on the code level and keep forgetting sometimes that theres a whole engine around my code. Thanks!
But now I kinda wanna know how it would be done ngl
Consider looking up a service locator pattern (basically just another abstraction layer for your singletons which allows for the implementation of a subscription/observer model) as this sounds like something you're trying to develop
and you're probably looking for this:
https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
Oh thanks! Yeah Im not really well read on patterns at all yet. Thanks for the pointers!
!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.
https://gameprogrammingpatterns.com/ I love this site for em'
StartCoroutine(CleanUp(cube));
private IEnumerator CleanUp(GameObject cube)
{
// Doesn't yield past 5 for some reason?
yield return new WaitForSeconds(4f);
Destroy(cube);
print("Cube destroyed? " + secondsBeforeCleaned);
}
I have this function that works except it doesn't yield if I use anything more than 4 seconds and I'm baffled as to why
Does it still destroy the object, does it print?
it doesn't print at all if I yield any higher than 4 seconds but it does print for 1 2 3 or 4 seconds
Then something else is likely destroying the object, since this coroutine isnt completing
but the cubes still exist after that they just don't ddestroy
Check if the object this code is running on is destroyed. It could be that this object is destroyed by something else within 5 seconds
Or maybe you set the timescale to 0 at some point
Oh my god your right it's because I have the script on the projectiles that hit the blocks but they clean up themselves after 5 seconds
If you want to ask things directly of other users that are of no value to others, do it via DM
Hi, my partner is looking to create procedural generated 3D caves, and I'm wondering if anyone knows anyone resources to help show how to do this. He's not interested in using Cellular Automata.
Google and YouTube.
Sebastian League has a few good tutorials involving marching cubes. Maybe they can use that.
Ok, thanks!
Can I have a Tilemap Collider change Scene when colliding with player, but the scene is specific with the Door using SceneManager.LoadScene(). Town door would be a difference scene, Guild door would be a different scene, etc.
You need to put some logic on the collider that defines what scene to go to and which spawn point in tihat scene to use.
I have logic for that, however it currently only teleports to one set scene, and isn't different for each door.
Each door has its own instance of the script. Insert a scene name or index that loads a scene when the collision event occurs . . .
Can you give an Example Code?
So change the scene on the collider to be a different one 🤷♂️
then I guess your logic is wrong
How are you changing the scene now on two different exits?
This is the Code I have: cs private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject) { Invoke("SendToHouseScene", 0.5f); } } void SendToHouseScene() { SceneManager.LoadScene("Housing"); }
just create a variable on your script: either a string for the name or an int for the build index to use for changing the scene . . .
You can't use Invoke on local functions
You have to move SendToHouseScene out of that function, to the class scope
also, use nameof(SendToHouseScene) to avoid explicit strings
I messed up pasting*
also, if (collision.gameObject) will always be true
I will change that. For now I just need assistance finding a solution to sending to scenes.
this code will always go to the "Housing" scene. You'll need to write some logic that checks something about the door and decides which scene to go to
I should have mentioned. This is the code I am using, but I know it doesn't work for sending Player to Multiple Scenes* I need help finding the solution for that*
check something on the door. Maybe put a script on the door that has the scene name to jump to
then you can just go to whatever scene the door says to go to
seems like a simple scalable solution
You can set the scene in the inspector for the door.
honestly, this is a simple issue of using a variable when calling the method to change scenes. i'm not sure where the confusion lies . . .
#archived-code-general message
#archived-code-general message
This is my layout of the map. The doors are highlighted, and are the ones I need to fix. They are all contained in one Tilemap called, "Door". I need each door to teleport to a different scene.
How? It is a Tilemap? ⬆️ I understand that you can still set it, but it won't be different for each door.
I'm confused on how to change the scene that the player is sent to. This is because the doors are all part of the same Tilemap and not individual sprites gameobjects.
Make the doors out of real individual GameObjects
Or - have a map of tile coordinate to scene name somewhere
and look up the scene name based on the door coordinate
seems like a lot of maintenance though
Is there not a simpler and efficient solution outside of those two?
each door has the same script attached to it. the script has a field - either a string (scene name) or an int (build index). for each door, set the appropriate value for the scene tyou want to change to . . .
That would be the same no? It will have all doors send to the same scene.
Door GameObjects seems pretty simple to me. You need some way to distinguish the doors. That would either be with GameObjects with a script on them, or tracking the tilemap coordinates somewhere
Yes it is simple. The issue is that the world will have at least 15+ doors. 😵💫
So? That is not that many..
You can even use the GameObject brush on the tilemap
you do know that placing the same script on separate GameObjects are completely different insntances, right?
Yes. But just incase I am reading correctly, you do mean this right? ```cs [SerializeField] string Scene;
void SendToHouseScene() {
SceneManager.LoadScene(Scene);
}
Then which part is confusing? How will that be the same? On each script attached to a door, you can change the value of the variable to whichever scene you want to change to . . .
It was just confusing to me on how you worded the sentence. But I give up on making this, let me just do as you guys said.
How can that be done?
Thank you! Never knew brush settings was a thing 😄
imo, i would not use tilemap brush for anything but testing
if you want to make custon levels with tilemaps, you should use Tiled. If you just want to use tilemaps to represent things programatically, you don’t need a brush either
hey
in Unity is there a interface system (maybe its not the same name as UE) ?
Like you have a "asset" or script that contains a list of functions with inputs and outputs, you can then add it to any object in game
then from another game object, you can check if this interface exist and call the functions, but no errors occurs if the function doesnt exist in given game object
tell me if i wasnt clear
note: after writing this message, it feels like a "interface" in Unity would just be a c# script
how would this part work but no errors occurs if the function doesnt exist in given game object ?
okay thanks
I don't remember if unity events make a check implicitly when you invoke them, but if not, it's just a matter of checking if it has subscribers or not.
Hey. Not sure if this is the right channel to ask and it's probably a dumb question, but yeah.
I was wondering why the second " and ) have a lower opacity than the first? (I'm using Visual Studio 2019). Reason I'm asking is because I know that, when I use brackets where not needed or "this.", etc., they get like that too. But not sure why they do here tho.
I'm surprised you've even noticed it.
Maybe minutes implicitly converts to string with this parameter?🤔
Oh, you might be right actually.
Highlighting over these should tell you why it's showing you this
strings inside string interpolation need to be escaped
hey everyone, i cannot figure out as to why the tile left of the king does not highlight, even though all the others do
how do i post code?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
https://hastebin.com/share/reberecago.csharp
link to the code
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i tried to copy paste it but it automatically converts to a .txt file, must be cause there are too many lines
You have (-1, 0) twice in the list of valid movements
🤦♂️ such a silly mistake
thanks for letting me know
i was also wondering if there is a way to reduce the if else statements in the row column check function
For one you don't need a special case for column and row 0. The second for loop just won't run in that case anyway.
same for column/row 7 actually
You could also merge the concept of checking row and diagonal in a single for loop.
List<(int dx, int dy) straights = new List<(int x, int y)>() {(1,0),(-1,0)(0,1),(0,-1)}
List<(int dx, int dy) diagonals = new List<(int x, int y)>() {(1,1),(-1,1)(-1,1),(-1,-1)}
foreach((int dx, int dy) direction in straights)
{
for(int i = 1; i < 8; ++i)
{
(int x, int y) position = (currentX + direction.dx * i, currentY + direction.dy *i);
if(IsValid(position))
AddToValidPosition(position);
else
break;
}
}
where does the diagonals list come into play??
i dont understand why i dont need a special case for column/row 0/7? can you explain your reasoning in detail?
Presumably you added those special cases because you don't want the second (or first) loop to run on those columns/rows, right? Well they don't run anyway on them so they're just unnecessary
List<(int dx, int dy) straights = new List<(int x, int y)>() {(1,0),(-1,0)(0,1),(0,-1)}
List<(int dx, int dy) diagonals = new List<(int x, int y)>() {(1,1),(-1,1)(-1,1),(-1,-1)}
List<(int dx, int dy)> availableMoves = new List<(int x, int y)>();
availableMoves.AddRange(straights);
availableMoves.AddRange(diagonals);
foreach((int dx, int dy) direction in availableMoves)
{
for(int i = 1; i < 8; ++i)
{
(int x, int y) position = (currentX + direction.dx * i, currentY + direction.dy *i);
if(IsValid(position))
AddToValidPosition(position);
else
break;
}
}
For loops check the condition before the first loop and just do nothing if the condition is already false
that notation works?
shit I’ve been using the tuple class, which is so confusing to understand later
no, i didn't take this into account, i just added those cases since they require checks in only direction
the pieces that are not on the edge require both sides to be checked thus i did this
Right but the "normal" case already skips the other direction there
so there's no point in making a special case
what I do for this sort of thing is I have a padded matrix/array
so if you have a 5x5 board, I make a 9x9 array or something, that automatically offsets itself when you access
then you don’t need to check edge cases, which are obnoxious
i still dont understand this, i will have to think about this more
you just need to check for null, which you would do anyway
idk if this helps for your case
i think i will try the within bounds method that i have already, but yeah this is a smart method to use
i have a lot of systems in my game that are on a grid, and I really don’t want to constantly deal with edge cases. a padded matrix helps me keep my code much simpler
let me see if I can send you simple code on git
thank you so much!!
sure. the docstrings should make it clear enough how to use
why use of ++i here?
To increase i ?
no, i meant why not use i++?
++i is the awkward cousin of i++
It is faster to do ++i then i++ due to how CPU works. It does not matter. The difference is abysmally small and CPU will probably optimize it anyway.
In other words, I'm doing it so I don't have to hear that from other team member
but doesn't using ++i cause the loop to offset by 1?
Nope
or am i wrong
i don’t think so
ooh
++i is just awkward when people use the ++ in the middle of a line where other things are happenning for some reason.
It is like if you did:
some instruction;
++i;
some instruction;
int a = 5
Debug.Log(i++) // OUTPUT: 5
int a = 5
Debug.Log(++i) // OUTPUT: 6
++i is faster than i++ a bit since no temporality register is needed to store the value before increment
the compiler will optimize it
so effectively no difference unless you call it in the middle of a line
with other things going on, as above
in which case what it does is actually just different
it is true for almost all cases unless you start to use pointer....
I left that life behind. I never want to see another pointer ever again
the seg faults and memory leaks scarred me
Tile question. I have a design for a tile that requires corners in terms of rule tiling. By symmetry, I have a little border that I could express with ~12 tiles (with different rotation/mirror symmetry). And a design inside that can’t be rotated, but can be expressed with maybe 9 tiles tops? If i have no symmetry, this would be like making 256 tiles, which is way too much.
Q: Is there a way to make a tile that displays like two tiles overlaid on each other?
- If i create an enumerator object once, can i re-use it to start multiple coroutines? Will they work when started simultaneously?
one instance? i don’t think so
Ienumerators do things by calling:
while (enum.MoveNext()) yield return enum.Current
if you have one enumerator, every MoveNext() call will advance it
unless start coroutine makes a copy? but it’s a reference type, so i don’t imagine so
- That's what i assumed. So if i ensure that one enumerator is only ever used once, i can reuse them by invoking reset on them first?
No you cannot. They are single use
No
What you can do is save a reference to the coroutine function itself in a delegate, and call that repeatedly
E.g. cs Func<IEnumerator> example = MyCoroutine; StartCoroutine(example()); StartCoroutine(example()); StartCoroutine(example());
- Which will still create new enumerator objects per call, but also cause extra overhead for delegate objects storage. The problem is garbage allocation in the project that relies on coroutines heavily, not the access to the methods
make separate instances
There is no way to avoid allocation with coroutines
If you want to avoid allocation, do not use coroutines
- I see. Unfortunate, but the only way to go ig. Thank you
as far as I understand, the main coroutine garbage is the new WaitUntil etc instances
The enumerator itself and the Coroutine object are also allocated
executing a method that returns an enumerator creates garbage
because an instance of a compiler-generated class has to be created
aren’t both those two objects super light tho?
They are light but if your goal is zero allocation they aren't zero
drop in the bucket imo
unless you spam them, everywhere. which has its own host of issues
but that becomes an architecture issue, not an allocation issue
- Even drops in a bucket eventually will fill it. Besides, the project i've been asked to optimize throws not drops and not even spoons but other buckets
- Yeah, this in a nutshell
coroutines are not where I would start optimizing
corotuines would be more a target to straighten things out
what I mean is that the use of coroutines isn’t going to be what crushes performance. it’s probably what they are doing
- Neither do i, but they're one of the top priority to me, since they hold a solid 6-9% of all garbage during a single one hour session
god damn wtf bro
- Ikr
- It's not me, it's a 2 year old project that *suprisingly* gets a disturbing amount of anrs that needs to be investigated
this is a very helpful class that helps me cut down on coroutines
it's a singleton with an extremely late early execution order. A lot of coroutines exist because you just want to execute one line on the following frame.
in those cases, I just subscribe a function to one of the delegates of this singleton
- Events also create garbage fyi. Sometimes less than coroutines, but it's not guaranteed
they should be mostly like function pointers
it makes a bigger difference if you have a coroutine with a while....yield return new WaitForFixedUpdate(); loop
because that shit makes garbo every fixed frame.
and it's a bit simpler to set something to execute just once with this pattern
given your case is a doozy, it is one option that might help
events making garbage is pretty surprising to me
i need to cut down of mine later on because of it
- The smallest single target delegate contains at least function and instance pointers, then you get parameters and local variables in the instances of the generated classes that they might point to additionaly to your type. Besides, delegates are immutable and will always reallocate when you add/remove something
I think he's refererring to the garbo that comes from actually calling delegate Combine
maybe this is worth benchmark testing.
im thinking of making my own event system and just deal with pointers myself
if you need to really optimize, maybe making a List<Action> might be useful. Then a singleton holds a block of memory that stays allocated
List<Action>, then .Add, .Clear, .GetEnumerator....
instead of +=, =null, ?.Invoke()
again, just lighter. people rarely make coroutines for the fuck of it. it's almost always because there is some timing aspect that needs to be respected.
- You're going to face many caveats, just saying. Besides, your code becomes really memory-unsafe and you have little to no chances to spot it (unless you have some cpp experience ofc. Which i don't, and i've been hang out to dry by just trying to use bare pointers)
- From what i see, most of these coroutines are just "wait random amount of seconds before executing that method" stuff, or just timers. Weird shit
the benefit of coroutines is sleeping them and getting somewhat accurate wakeup times
otherwise I'd just do it all in a single updateloop and poll them
so runtime performance vs some garbage
which equates to performance too, but effectively polling hundreds through update is probably the worse of two.
for (int i = column + 1; i <= 7; i++) // check in the right side
{
if (!IsOccupiedByWhite(row, i) && !IsOccupiedByEnemy(row, i))
{
_listOfTilesToHighlight.Add((row, i));
}
else { break; }
if (IsOccupiedByEnemy(row,i))
{
_listOfTilesToHighlightRed.Add((row,i));
}
}
Will the break cause the loop to exit without checking for the IsOccupiedByEnemy?
you have two IsOccupiedByEnemy here
so how do i circumvent this?
i want to check whether the tile is occupied by enemy or not as well
why do you have else { break; }
continue? actually you probably have that statement below for a reason haha
not sure of the use case here
if (IsOccupiedByEnemy(row,i))
{
_listOfTilesToHighlightRed.Add((row,i));
}
else if (!IsOccupiedByWhite(row, i))
{
_listOfTilesToHighlight.Add((row, i));
}
else
{
break;
}
if a tile is occupied by a piece, suppose a white piece, in that case, i do not have to check further since i can only highlight till that point thus using break to immediately break out of the loop
that's not what break does
maybe start by correctly enumerating a tile's adjacent tiles
oh yeah this works, thanks a bunch
chess boards are small. there are better and more expressive ways to do, "where can a piece move?" you don't want to be intermingling the concern of a valid move with which tiles to highlight
i cant find a way to use a custom enum as the keys of a dictionnary
//global
public enum ElementsType
{
None,
FloorBox
}
// in class
private Dictionary<ElementsType, int> _actions = new Dictionary<ElementsType, int>()
{
ElementsType.FloorBox = 1
};
what could be the issue ?
why not just use the enum if you're doing int to int
probably need to use brackets []
im debuggin step by step
ElementsType.FloorBox is a constant and you cannot assign a constant
where ? on the examples i found on forums its like on my code
ah
you can set the enum value in its declaration.....
im pretty sure you can
public enum A{
a=10;
}
timers make sense. that many timers does not
is it not only int ?
you can, but it is better to use an array and assign it by index
{key,value}
you mean using the int in the enum as the key to access whatever in the array ?
ty
but i still got one of the errors
Show code
array[enum]=something or
something=array[enum]
and set the enums' value sequentially, start by 0
private Dictionary<ElementsType, int> _actions = new Dictionary<ElementsType, int>()
{
{ ElementsType.FloorBox = 1 }
};
it is , not =
That's not what I showed is it?
im tired, sorry
yes mb
well now i got some issues with storing a function as a key
you make key to delegate
i tried following this https://discussions.unity.com/t/dictionary-of-functions/152737/2 but it tells me i cannot convert a method group with a action
wdym ?
That thread is about functions as values
What exactly are you trying to do? Having functions as keys is ... peculiar to say the least
oml he was right. giant delegates have massive cost to +=
ye need to make your own pointer management script
imma make one eventually because I bind and unbind tens-hundreds of event per item equipped
pretty expensive
After some time i changed my process to a easier one, no need for that dict anymore
I appreciate your fast responses
I need another 16gb of ram, my current PC uses 16gb Tridentz Royale 3200mhz. I'm trying to get something that is compatible with my board and ram. The board is Asus Maximus xi
I get too many slowdowns
Not related to Unity or Coding
download code more ram
Coding requires ram
Same with unity
Unless you just code on paper
who says you need to run your code
Ok cs teacher
Please don't spam the channel with your personal issues.
you can use mmap to use disk space as additional memory
Please join the mod team
I hate swap memory
for (int i = row + rowDirection, j = column + columnDirection; IsWithinBoardBounds(i, j); i+=rowDirection, j+=columnDirection)
{
if(IsOccupiedByEnemy(i,j))
{
_listOfTilesToHighlightRed.Add((i, j));
}
else if(!IsOccupiedByWhite(i, j))
{
_listOfTilesToHighlight.Add((i, j));
}
else { break; }
}
there is one more issue i am facing, i want to exit out of the if loop once the IsOccupiedByEnemy is true, since once it is true, i don't have to check for the enemies behind it since i cannot reach them
@glass berry There's no off-topic here
I'll go compile my code on a calculator then
then you can break the loop after the first if block
make use of break; and continue; in your loops
if i use break, wont it exit out of the for loop as well?
isn't that what you want
if you had multiple loops, one inside another, break; will break out of the current loop.
But since this is the only loop then you break; out of this and continue on with your code
i dont, in the case that are iterations left where the tiles wherein the checks are left to be made for the white pieces
ahh
thanks
nope actually that wont work i guess
can always create flags beforehand if you need some for inside of the forloop
or inside if you need them for the current iteration
You already have one break inside the loop that works as you want it so I don't see why another one wouldn't do the same
omg the source code for action is attrocious
public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7,in T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
for every individual number of arguments, they just defined a separate generic lol
ah shucks I needed 9 of them
There's no mechanism for variable number of arguments in C# so there's no other way to do it really
I think everything needs to be the same type if you use params
i remember tuple does the same thing
ok, so I'm trying to make an equivalent class for big Action delegates, ones with a ton of +=/-=, and balloon to big sizes, by implementing as a list. is there a way to define it as an event, to keep syntax like only exposing += and -= outside the class that does not own it?
Question, if I have a from vector and a to vector, how can I check if the closer direction to reach destination is rotating clockwise or counter-clockwise?
Euler angle vectors?
You could use quaternions and unity would automatically rotate it the shortest way
like, do you have a vector from A to B, and B to C, and need to know how to turn A-B towards A-C?
My enemies has a forward vector, and my target is in a different direction. Should it rotate clockwise or counterclockise to look at it?
you've two points which gives a direction, I'm not seeing any rotation here
you mean two transforms then
he has the inverse problem of a rotation matrix
he has an in and out vector, and wants to know about the rotation operator that moves in towards out
I think
I have the transform's forwards, and a direction which is (target - enemy).normalized. And I must rotate the first one into the second one, by rotating the enemies in the Y axis
turns out, i was overthinking it, yeah i just needed to add break
Oh, didn't thought.
I may try
There are so many ways to do it.
You could lerp the forward vector.
You could lerp the rotation angles.
You could lerp the rotation quaternions.
You could use one of the Rotate functions.
The list goes on...
The only thing I need is actually a float or bool which tells me if I have to rotate clockwise or counter-clockwise from the Y axis, and maybe the rotation intensity. So I don't actually plain to ler or rotate functions
then just get Mathf.Sign on the SignedAngle
Q: I want to make a bunch of ruletiles that have very simple patterns like this, and I think I should be able to do this programmatically. There is a lot of symmetry here, so I'd theoretically only need to uniquely draw: inner corner, inner corner between 2 walls, wall, and open side. But i need to draw a lot of combinations, despite all the symmetry. Is there a smarter way to do this via code?
prefabs?
Also, I just tested benchmarking a giant delegate with 100k += operations on it. It is extremely slow, and that scales as n^2. Replacing it with a list implementation makes it way faster. Adding a function to the delegate becomes totally free. And removing a function from delegate is still much faster. The time to fully += 100k, then -= 100k was 10x faster with list implementation
this is on tile assets, to make sprites
I need some help... I'm trying to apply "x64" in the checkbox under Standalone->Linux on a native plugin, but when I press "Apply" it goes back to being unchecked. I imported the same plugin into a different project and I can check it no problem. I also double checked that it's compiled for 64 bit platforms... Anyone know what to do?
Hi. Im currently trying to code a Volleyball game in unity. I have done basic movement and also the field setup, (its 2d) but what I dont manage is that I want the player to have to press specific button-combos in order to perform specific volleyball moves. So in this example, I want the player to first click "Q" and then choose one of WASD to choose what side hes gonna set the ball to. This is my code:
private void Setting()
{
if (Input.GetKeyDown(KeyCode.Q) && Ball.transform.position.y > transform.position.y && Ball.transform.position.y < transform.position.y + 1)
{
rb.isKinematic = true;
if (Input.GetKeyDown(KeyCode.W) && !Input.GetKeyDown(KeyCode.D))
{
ballrb.AddForce(transform.up * 30);
StartCoroutine(Wait());
rb.isKinematic = false;
}
else if (Input.GetKeyDown(KeyCode.D))
{
ballrb.AddForce(transform.right * 30);
StartCoroutine(Wait());
rb.isKinematic = false;
}
else if (Input.GetKeyDown(KeyCode.W) && Input.GetKeyDown(KeyCode.D))
{
ballrb.AddForce(transform.right * 20);
ballrb.AddForce(transform.up * 20);
StartCoroutine(Wait());
rb.isKinematic = false;
}
}
}
Right now its the raw version without any timing tries, I didnt manage so I kept it like this. Could someone tell me how to modify it in order to make the player be able to have a little time window (say 1 second) to press the next button?
Thanks!
!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.
There you go :)
You should make a new class named 'InputCombo' with a list of InputKeys. Every Update you check if the next key in the list has been pressed.
If it has you increase the index until every input has been activated.
Then you can also add a timer that resets the index if no successful input has been achieved in X amount of time.
I'm gonna give it a go, may I show you what I came up with for additional help?
sure
The method doesn't allow me to define the plane of rotation. The axis is only using to determine if the result must be flipped. How can I determine I want the angle of an specific axis?
if you only want those 3 combos you might also keep what you have and split it into two parts. The first checks if Q has been pressed which toggles a bool to true. Then if that is true you check for the other inputs. Also your Wait() Coroutine is almost certainly not working.
yea the coroutine doesnt do much, well how would i add a timer then?
say I want to give them 1 second or 2 seconds to finish that combo
for 3D, you want to project your two vectors onto a plane
define a plane with plane normal b. To project A onto B, the projection is proj = (A dot B) * B / (B dot B)
float timer;
bool hasPressedQ;
void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
hasPressedQ = false;
}
if (Input.GetKeyDown('Q'))
{
timer = 2f;
hasPressedQ = true;
}
}``` @bright token
which is the same as (A dot B.normalized) * B.normalized
then A - (A projected onto B) gives A projected onto the plane to which B is normal.
Vector3.ProjectOnPlane?
ah, well that would probably do the same thing
I mostly work in 2D
but you do want to do a projection.
I see... so in the Update function or in my setting function that is called in update?
if you are projecting onto a trivial plane (like x-y plane), then the projection is trivially (x,y,0)
doesn't really matter
Ok, thanks
private void Setting()
{
timer -= time.deltaTime;
if (timer <= 0)
{
setcombo = false;
}
if (Input.GetKeyDown(KeyCode.Q))
{
timer = 2f;
rb.isKinematic = true;
setcombo = true;
}
if (setcombo)
{
if (Input.GetKeyDown(KeyCode.W) && !Input.GetKeyDown(KeyCode.D) && Ball.transform.position.y > transform.position.y && Ball.transform.position.y < transform.position.y + 1)
{
ballrb.AddForce(transform.up * 30);
rb.isKinematic = false;
}
else if (Input.GetKeyDown(KeyCode.D) && Ball.transform.position.y > transform.position.y && Ball.transform.position.y < transform.position.y + 1)
{
ballrb.AddForce(transform.right * 30);
rb.isKinematic = false;
}
else if (Input.GetKeyDown(KeyCode.W) && Input.GetKeyDown(KeyCode.D) && Ball.transform.position.y > transform.position.y && Ball.transform.position.y < transform.position.y + 1)
{
ballrb.AddForce(transform.right * 20);
ballrb.AddForce(transform.up * 20);
rb.isKinematic = false;
}
}
}
testing now
Thank you! I already asked in the c# server and got no answer at all, its been almost 2 hours. You answered quickly and helped me so much
it works :)
btw you can check for the Balls y position at the start of your if (setCombo) statement. Then you need it only once.
true
How do I get a random coordinate from a navmesh
So I can spawn enemies in a valid location randomly
many different ways. you can do X/Y for size wise then do a https://docs.unity3d.com/540/Documentation/ScriptReference/NavMesh.SamplePosition.html
https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html a random point inside https://docs.unity3d.com/ScriptReference/AI.NavMeshData-sourceBounds.html
this will have biases. there is no general way to select a random point on a navmesh (inside a navmesh) in exactly 1 call that gives uniform likelihood for each point. you can repeatedly sample for small distances until there is a hit for a uniform likelihood, but that may be unexpectedly slow. usually you want enemies to spawn on poisson disks and not uniform random (see image https://repository-images.githubusercontent.com/274968879/4de75d00-c818-11ea-90d9-ba023a3bbe64) this will have a bigger impact on game feel then better random selection
Ah navmesh data has the bounds, I was looking on NavMesh class
this will have biases. there is no general way to select a random point on a navmesh (inside a navmesh) in exactly 1 call that gives uniform likelihood for each point
also depends how far/random it needs to be..
Eg my enemies generally spawn closer to player point so a nice Random.insideUnitsphere works with SamplePosition
How would I calculate a % from 0% to 100% based on the input that gets increasingly bigger?
Something like a Tween probably.
For example experience required formula that goes from 10 to 1000, but from level 1 to 10 the total is 100, but 10 to 11 already requires 50 etc. Up to max level of 20(19 to 20 would require like 300xp)
What do I need to achieve something similar?
I think Tween might do the trick, but I am not sure.
So the total exp from 1 to 20 = 1000, but lower levels require less experience.
yeah, what do I need to make it happen?
I found something called Weighted Random, so I probably need Weighted not random 😄
based on the input
ohh thought you wanted this
https://youtu.be/GDcgsJKl7WY
This tutorial will feature use of animaton curves to make a quick visual experience system which can be easily modified and built upon!
Great Related Video (Animation Curves) ► https://www.youtube.com/watch?v=Nc9x0LfvJhI&ab_channel=GameDevGuide
Project Download ► https://github.com/ItsPogle/Leveling-and-Experience-using-Animation-Curves-in-Unit...
no I need like a math behind it
just use this
I am searching for weighted but everything I get is for random numbers lol
I'd prefer something I can control myself, dont want to add assets from outside.
I did that once before based on someone recommendation and I regretted it later 😄
Also its for random numbers with predefined %, I need something that works with different amount of items.
actually reading what you're asking I dont think a weighted random would be applicable here
what's wrong with a curve again?
I don't know what curve to look for
Is it a good idea to use animation curve for non animation code?
what does this even mean
tell me you didn't watch the video by telling me this
well there has to be a formula for that curve right?
why do you need the formula..
I thought the video you posted was for animating the progress bar.
you're just looking to formulate your own experience gain. Usually games do stuff like an exponential curve of some values but it's up to your design
ok let me explain it a bit better
did you ever bother typing Animation Curve + XP in google ?
I want to set max exp number, like 10000
This is how much exp you need to reach max level.
max level can be anything, but lets say its 100.
If you go from level 1 to 2, it will use like 0.5%(50) of the 10000
from 99 to 100 it will be like 10%(1000)
you can do a ticket type system. Every item gets a certain amount of tickets, you put all the tickets in a pot and draw one. Whichever item the ticket belongs to is selected. The more tickets you give an item the higher the chance for it to be selected and you can easily add more items without having to readjust all the values.
I feel like this is wrong to use Animation curve for things not related to animations.
animation curve name is misleading but its just a curve(actually yes sampler is better term because you can make other shape not just curve) .
your curve would be exp per level
same thing as typing it manually with as you say, a formula..
Animation curves are super versatile and used lots of places
I use them for idle games value plateaus for example
exactly, I use it for movement for example
when i want my player to accelerate nicely
ah ok so its like Tween, a generic class that can be used eveywhere.
I thought its like Animation based class that has Animation based properties or something.
I will check it then.
perhaps do more research when someone suggests something lol
Like you said the name is misleading 😄
agreed
Ok quickly coming back to you, i advanced a lot and now Im at the part of serving the ball, that one is supposed to be with a real combo of buttons, not like the other one where I pressed "Q" to prepare and then the button in the direction I want it. You said to make a class with a combo list, but I have no clue what that would look like since I just came from 1 year of working on python projects, could you quickly get me in?
but i assume that was its original usecase ?
not sure what unity's thought is there
if you want exacts then you should just formulate your own function
Well you suggested it but then posted a video with animated progress bar so I assumed you got it wrong, cuz it was related to animating a progress bar.
nah if you warch the video they do logic for AnimationCurve xp level increase variance
yeah I didnt know where to even start.
I will keep in mind "curves" for the future, already finding some stuff on google 😄
what's the proper way to load a uxml document/uss style to create a custom control in c#? For now I'm loading it from resources but I don't like the idea
I mean, using UIToolkit
i really should learn UIToolkit 😔
I don't like the idea of using the resources folder because I intend to have one single project with multiple scenes that will be build separetelly, if I add everything on resources then they'll always be included in my build
You'd think this would be pretty simple but I need a dang triangle 2D collider. Polygon colliders sinks performance and the object simply doesn't move if I change the polygon settings at all. any solutions?
[System.Serializable]
public class InputCombo
{
public List<KeyCode> keyCodes;
public Vector2 hitDirection; //The Vector to be applied to the ball if success
}
--------------------------------------------
public class ComboChecker : MonoBehaviour
{
public List<InputCombo> Combos;
private List<KeyCode> currentKeyCodes = new();
public void Update()
{
int currentIndex = currentKeyCodes.Count;
foreach (var inputCombo in Combos)
{
KeyCode keyCode = inputCombo.keyCodes[currentIndex];
if (GetKeyDown(keyCode))
{
currentKeyCodes.Add(keyCode);
return;
}
}
}
}```
This keeps track of any inputs that match one of the combos.
You can assign the inputCodes in the inspector. It might be better to make that a ScriptableObject for easier editing.
It would probably be better to keep a list of all valid Combos, i.e. if the player pressed Q only check Combos that start with Q and discard the rest until we reset.
ive never really looked at "triangle colliders" but you can just type in "collider" in the component field and see various kind of stuff you can try
is the second class supposed to be a new script? or what is that line ------------------- to mean?
Yeah I've tried all the different types of colliders. Edge colliders seemed like the best candidate but they weren't colliding for me.
How can I change the name shown on the inspector of a variable without writing a custom inspector?
Like something like this:
[RenameVariable("Fake name")] public float internalName;
I did it a while a go but don't remember how
https://forum.unity.com/threads/physics-collider-2d-triangle.100884/
dunno if this works but google gives answers
Do you mean FormerlySerializedAs ?
thank ya
yes
I did see this, just seems like an incredibly janky solution to something very simple if i understand them correctly. Will take another look
ok ok wait I wanna try to follow
I just pasted the first part into my player script and the 2nd one to a new script
i get the error "InputCombo" could not be found
you need both in a separate script
yes I did that
im gonna start a thread if its ok, dont wanna have a conversation only about my problem filling this whole channel :P
InputCombo is a class that holds a KeyCode list for the combo, i.e. 'Q-W-W' and a Vector2 which will be the force applied to the ball.
ComboChecker has a list of all InputCombos the player can do and a List of KeyCodes that keeps track of which keys have been pressed so far.
is there a decent workaround to not being able to make static virtual/abstract methods?
I have a base class with a static method, where it wants to call a static method, which depends on which class it derives from.
....static virtual/abstract isn't allowed. And I would need an instance to call a non-static method
Trying to have an action fire only when the right mouse button is released, but these settings don't change anything, it still fires as soon as I rightclick
The "Boost" action is a button with no interactions/processors
show where you are getting the input and acting on it
in my Player prefab:
well you still haven't shown the Boost method where you're actually acting on that input, but i'd bet you're not doing anything like checking what the phase of the action is. realistically you don't even need that interaction on your input action and can just react to the canceled phase
ah my bad, here's the actual method
but yeah for every other actions I've been able to just call the method by linking it in the player controller, I don't understand why I suddenly need to do manual checks when there seems to be an option to only fire when releasing the mouse click
please read the documentation pinned in #🖱️┃input-system to learn how to use it
Hello, is there a not read-only alternative to Application.persistentDataPath? I try to edit the file after I saving it
the Application.persistentDataPath property is readonly. that doesn't mean the files you write to it are
of course the location of the path and how that path works depends entirely on the platform you are building for
aah ok that makes sense. Thank you 🙂
this is a code channel. but check the scale
Application.persistentDataPath is read/write on all platforms
i have no idea why its doing this. Seems to spawn an invisible collider that doesnt exist upon pressing play.
i dont have anything in my scripts that would spawn a second collider
!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.
also screenshot Inspector for it (player)
capsule
player game object
nothing else player related has colliders or rigidbodys even when on play
you're mixing a rigidbody and a character controller which is a no-no. also the charactercontroller is a collider
ahhh i knew it was something as simple as that
thx
I realize that was left on there before from a previous script revision that i forgot to remove
is there a way to put a class in a namespace without the whole thing being super indented?
not in c#9
You can just not indent 🤷♂️
I've seen plenty of people do that
You just have to do it manually of course, which is annoying
what you want is filescoped namespace
only avail in c# 10+ unfortunately
namespace Coolness;
class Foo
{
}```
🥲
Heres my scoreboard
Heres my player
i cant get the text to update when the player touches the flag
right now i get
configure your !IDE
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
Use void type
i just did that
now its all looks a little different
that didnt work, thank you anyway
they're suggesting you change the constructor into a void method
public void UpdateScoreboard()
Hey guys, I currently have code that sets the aim direction for an FOV mesh but does so instantaneously where as I'm looking to Lerp it instead to the target Vector3, would anyone have any good ideas to convert this
You could use Vector3.Slerp or Vector3.RotateTowards
I was thinking the same but the issue im having is that Starting angle is a float and Idk if its just not clicking but im having trouble connecting Vector3 Slerp into the float
What does startingAngle do here? Do you want to use it to define a direction on some axis?
Its connected to a mesh and is essentially the left most side of it
i can grab a hastebin
I'm still unsure how it's supposed to work
But you could just Slerp or RotateTowards from current transform.forward to aimDirection, no?
!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.
oh interesting
I think the main Issue Im having is I am calling the SetAimDirection every frame, which isnt quite allowing me to lerp because Im not giving it time to lerp
this is just the part
to horizontal movement
I put it in update
moving rigidbody in update is bad
it goes in FixedUpdate
inputs are read in Update
it work?
I'll rebuild tomorrow its too late rn
I tried it on the editor and once I put it on fixed update it started working like in the build so it might be have worked already, now I can adjust the values accordingly
thank you
sounds promising then , goodluk!
let's say I have one component where I need to do a LOT of TryGetComponent calls. Would it be a good idea to speed it up by adding:
public static IReadOnlyDictionary Directory => dict;
private void Awake() { dict[gameObject] = this; }
private void OnDestroy() {dict.Remove(gameObject);}```
Good idea? bad idea?
Sounds bad to me. Also looks like a leak waiting to happen
that’s my first thought, but it seems like unity would ensure this won’t leak? Given I do need to to a huge amount of TryGetComponent calls for just this one component, what would you recommend?
by huge, I am trying to get rid of several thousands of these calls per frame
i’m also not a big fan of dumping a ton of memory onto the heap
For anyone else who gets this issue, the solution is to Lerp the input into the function instead of trying to reverse engineer the starting angle
maybe I should do a similar thing, but on a singleton holding the dictionary?
If you Destroy one of those objects you are still holding the reference in the dictionary, and because it's static it won't even be cleared when this object is destroyed
so unless you're careful you will hold onto those objects in memory for the lifetime of the program
i’m mostly at the mercy of OnDestroy, which is always kind of wacky
Btw, I don't think this is linear.
And it's not just cause you're using output as the input for lerp.
Your right I just switch to Slerp, it doesnt look like it makes an immediate difference but Im sure its my testing enviorment
.
I guess, try to imagine a box, and imagine another rod in the middle of the box.
Then imagine the rod rotates. The rate of change depends on the contact point in the rod and the parameters of the square.
I'm not sure if I can get the analogy correct. :p
yeah, if u get to the corners its gonna change the speed
I cant quite explain how to fix the issue i was having so I hope the code can explain itself
The right way would have been to get the angle of the aimDirection and the currentDirection and lerp the angles then convert back.
In the SetAimDirectionFast, looks like you just set the currentDirection to the aimDirection but did some extra steps converting it into degrees then back into vector.
So once I have a system of complicated interlinked scripts, What is a good way to not get lost in it all. I know of flowcharts but are there any alternatives?
Or is this the life ive cursed myself too lol
Maybe a mindmap depending on the structure.
But I'd say this kinda sounds like you want to refactor
Removing interdependence isn't always possible, but reducing it is always preferable
Anyone have problem with jittery movement when timescale is decreased for slowmo? Like everything else is smooth slow mo but the physics stuff moves obviously in large steps.
I've doing movement on fixedupdate and use FixedDeltaTime. Rigidbodies are kinematic and I set their transform position on FixedUpdate. Enabling interpolation does not help.
You're setting Transform position manually, interpolation won't kick in for that.. naturally you will get jittering from using FixedUpdate
Rigidbody interpolation only works when you're moving via the Rigidbody
You are bypassing the physics engine
Either use the physics engine to move (with interpolation on) or move in Update
I moved it to fixedUpdate due to various issues. Thought about moving it back but just wnated to be sure. Thanks.
FixedUpdate is correct, just move it via physics instead of transform. rigidbody.MovePosition will work with interpolation
Ah yeah, kinematic is probably fine in Update too
can someone help me fix this error? error CS1703: Multiple assemblies with equivalent identity have been imported: 'C:\Users\Jake\My project\Assets\UnityDemoGame\Assets\System.dll' and 'C:\2019.4.11f1\Editor\Data\NetStandard\compat\2.0.0\shims\netfx\System.dll'. Remove one of the duplicate references.
error CS1703: Multiple assemblies with equivalent identity have been imported: 'C:\Users\Jake\My project\Assets\UnityDemoGame\System.Core.dll' and 'C:\2019.4.11f1\Editor\Data\NetStandard\compat\2.0.0\shims\netfx\System.Core.dll'. Remove one of the duplicate references.
Remove one of the duplicate references
how do i do that?
why do you have a system.dll in your project and, more to the point, how did it get there?
sorry i'm kinda new to unity, just imported some assets, where does the system.dll go?
sorry, but I doubt that very much
Heya guys, I'm having trouble with this one particular piece of code that's not running for some reason.
I don't really know where to begin
How do people go about having consoles in their game? Do they write all the available commands in seperate script to process them all or is there a way to put a tag on a function so that they can just call static functions with the params?
Consoles usually show available commands when typing so all available commands would need to be listed somewhere to allow filtering
that worked thank you my friend
No worries. That's what lssply was pointing out
Need some help solving some code
the method I am using is very inefficient and is causing a lot of issues rn
So I made a script tied to an object that has DontDestroyonLoad but there is a UI button in the scene that has a reference to it. The issue comes when we deload and reload the scene, the UI button would lose all reference to that gameobject and script
Im relatively new to unity so ik using singletons and ddols are very inefficient
But I do need a solution to fix this
You'd need to reassign any references after the reload.
How do I reassign to an onclick of a button component?
You don't. Which is probably why you should subscribe to events via code. You can invoke a method in a script on the same object from the button. The reference to it won't get lost.
Ive been told to not use singletons for this case since it is very inefficient
And invoke a C# event(Action or custom delegate) from that method.
Theres a few ways, this may help: https://www.youtube.com/watch?v=VzOEM-4A2OM
Im sure you could setup your own attribute for functions and generate the list with Reflection, what ive done for my game is just made a static class that holds a dictionary of the commands I want, and more-or-less display that dictionary based on how many letters match a key, similar to a "search filter" - if you mean logging Debug.Log messages to a in-game console, theres also this: https://docs.unity3d.com/ScriptReference/Application-logMessageReceived.html
Learn how to create an in-game console that will allow the user to input cheat commands. Perfect for debugging builds and hiding fun easter eggs into your game...
Interior Mapping Shader: https://www.youtube.com/watch?v=dUjNoIxQXAA
UI Line Renderer: https://www.youtube.com/watch?v=--LB7URk60A
Making UI Look Good: https://www.youtube.com/watch?v...
What does it have to do with singletons?
I need help configuring visual studio 2022. My code does not autocomplete anymore within visual studio itself and intellisense. Visual studio also does not highlight classes and functions of unity. I have tried to follow all step in IDE Configuration but visual studio still does not work properly
So im alittle worried thats what is causing myy issues
Thanks Dibble, I appreciate it! I'll take a look at those resources
It might be contributing to the issue. But there's nothing wrong with singletons in general. If used properly.
Hard to say anything without seeing your code.
Ye i would share it but there are like 3 different scripts
And I dont want to clog up the chat
I have tried:
- Edit > Preferences > External Tools > Select visual studio > External Script Editor > Visual Studio 2022 [17.8.34330]
- Checking for updates within the package manager of unity. There are none the current version I have is 2.0.22
- Checking for updates within visual studio, there are none. The version shown is [17.8.3].
- Installing and reinstalling the game development package within visual studio 2022
- I have dotnet version 8.0.0 installed on my computer
I hope this information helps for solving the issue
screenshot your VS window
btw not a code problem
close vs. in Unity preferences regenerate project files, open vs, screenshot again
hmm, still not right, screenshot your External Tools window
I meant Preferences->External Tools
Select Player Projects and Regen
Really you only need csproj files for embedded packages and player projects, the rest can be turned off
Alright I changed it to only those options
Now visual studio also looks look way more clean
should clean up your solution explorer in VS as well
Yeah
I’m having similar issues and have a strange issue where i can’t click the player projects checkbox?
do not ping people into your question
anyway sreenshot complete external tools window
Sorry, VSC, I don't use it
ok, i'll try download straight VS and see how i go, cheers!
if you want the easy install option. Install another version of the unity Editor via the Hub and let Unity do all the heavy lifting
Is it widely known that unity2D-collision detection for an individual object stops working if you ever directly set transform.position(but directly setting rigidbody2d.position)works perfectly fine, no matter the type of rigidbody)?
I think I understand why it happens(rb pos and trans.pos are not reading the same value and might differ due to simulation and interpolation concerns), but the fact that it seems to break permanently for as long as the object in question is loaded and is never mentioned in any of the documentation has me wondering
in unity 2D, on a what is the intended best practice solution for doing collisions in a game or system that does not intend to use simulated physics(Outside potentially collisions through the physics system)?
If you're using collisions, you're using the physics simulation.
If you really want to rebel, you could use physics queries, but imho that's an ugly solution. Might hit the performance as well.
yeah, I meant in the sense of actually simulating 'real world' physics
I guess my intutition is that if you want say basic AABB-collisions in unity, you use boxcollider
if you are using physics in any shape or form then you use rigidbodies, if you do not you use transforms
In unity 3d that is not always true though, there are many situations where as far as I understand it directly setting transform.position even on a simulated object is the 'correct' solution
and it certainly never breaks the collisions
not to shit on unity2D
For example?
setting the transform will always break physics
Break them in the sense that they have to resimulate, yes
but not break as in they are now-non functional
No. There's no "resimulation". It breaks different things like collision, interpolation, etc..
It does.
it breaks them in the sense that the situation is indeterminate
yeah thats what I meant
youre probably right or were just saying the same thing
All Im really trying to ask is: Say I have two squares, and I want unity2D to give me some sort of message or hookable event when they overlap, without having to write custom AABB collisions or whatever, what is the best practice/intended way to do this
?=
physics triggers
rb + trigger collider?
yes
huh
Or as I mentioned previously, you can do physics queries every frame(overlap box or something).
- Does monobehaviour's invoke method works on local functions?
Yeah that is the fallback solution I guess. It just seemed strange to me that there was no in the box solution where I could both set exact transform positions and have collisions. But now I know RIgidbody.position is the way I guess its all good
Probably not. But you can try and see for yourself.🤷♂️
i think you need to know the name after compilation
ie you need reflection
Hi there!
I am searching for someone who could possibly help me with Unity Render Streaming. I was able to set everything up, I can receive the Audio as well as the Video-Stream in my browser.
Unfortunately I need to send the Microphone input from the browser to the Unity-Application and I am struggling with that. I tried a lot of things with the Audio Stream Receiver and Sender. The Bidirectional Scene is not even showing me options for Microphone or webcam-Input, so I am currently working with the Video-Player-Sample. I would realy appreciate if someone could help me out.
There is a way when importing a package from code via AssetDatabase.ImportPackage(package, false); determine in code which folders will ultimately be imported and appear in the project?
i.e. I did the import and I got these folders, I can somehow get them, so that later I can save them in json and delete them if necessary
i avoid Monobehaviour Invoke tbh.
hard coded strings are bad juju
you’ll be cursed for using them
You can use nameof to reduce the issue that you have with string method name
i see. wouldn’t that invocation still be pretty slow? because invoke is still searching by string?
for reference, this guy is specifically trying to optimize his game because like 10% of all computation time is spent on coroutine and related stuff
{
switch (slimeType)
{
case SlimeV2.SlimeType.Normal:
return NormalSprites;
case SlimeV2.SlimeType.Fire:
return FireSprites;
case SlimeV2.SlimeType.Water:
return WaterSprites;
default:
Debug.LogError("Unknown slime type: " + slimeType);
return normalSprites; // Default to normal sprites
}
}```
Anyone know how I could automate this process for all my slimeType enums?
anything could be automated, not sure what you need to automate here.
as i have a bunch of slimeTypes:
{
Normal,
Fire,
Water,
Alien,
Cat,
Cyclops,
Kraken,
Leaf,
Shark,
}```
I am probably going to opt to manually add them in everytime i decide to add a new type
Enum.GetNames, Enum.GetValues, Sprite[][]
that would not solve the issue, or perhaps I misunderstood the question (last post by op)
I'm not sure what you're referring to by automate but you could avoid having to hard code this get function by populating a collection such as a dictionary or list/array.
This is just a guess, but the first time invocation/reflection is probably slower but the following ones are faster
Coroutines are class objects so they have their small GC overhead too
And doing new WaitForX instead of caching it will also produce garbage
I ended up adding more cases to my GetSpritesArray, not sure how performant that is tho
The compiler might turn the switch statement into a dictionary anyway
At least that used to be the case with something like 8+ items
Dont worry about switch performance, is what Im trying to say
Awesome 🙂
So do what is best organized for you
It's been fun trying to make my game more optimal, ive tried to use more managers that target all my slimes instead of having massive bloat of scripts on each slime
If you ever get more than 50, consider populating a list from the inspector and access using enum as int or whatnot.
Else a switch is fine for a manageable dataset - relative to size.
i can get around ~200 and it seems runs fairly well on mobile surprisingly
no animations yet tho
I don't think it would work. Localfunctions kind of special(sorta), weirdly enough in plain c# via reflection you'd need to get it via regex and it's marked as internal static unlike any other normal functions. that said, I don't think the good ole MonoB' Invoke cover that
It's just a lot of copying and pasting. Editing can also be a nightmare that can potentially break stuff
Don't use enums, use ScriptableObjects instead
Hey all. I am trying out the new input system and i made a little Vector2 setup with WASD. Im using ctx to store my values in a Vector2, and am moving my player accordingly. Only problem is, once i press a value it never resets to 0,0 when nothing is pressed. Anyone know why?
you're probably not subscribing to the canceled event
yep
you're only subscribing to performed
the zeroing out bit happens in cancelled
ahh
honestly for every frame movement it's a lot simpler not to use events
just use update
void Update() {
movementInput = input.CharacterControls.Movement.ReadValue<Vector2>();
}``` that's my recommendation
alright ill try that out, thanks!
also, i can normalize my Vector2 either in action or in binding, which is correct practice?
there is no correct practice, it depends on your needs
Normalizing in action feels right then, movement works now by the way so thanks again
Hey y'all. I've here with a question on optimizing my rhythm game.
Would it be a good idea to pool notes here? I will never be able to anticipate the amount of notes in a map, so I'm unsure if pooling a large amount of gameObjects will work, especially if there is a section of map with an extensive density of notes. I just want to support pooling with maps with just under 10,000 notes (mappers have insane difficulty barriers), and note densities up to 30nps (notes per second)
I currently use Instantiate, but I typically don't find much overhead however I would like to be careful for later.
pooling is always a good idea, and you don't really have to pre-create a bunch of notes, you get a lot of optimization just from not having to destroy old objects
the node should disappear after player presses it or time out?
return it to pool and reuse the note gameobject
I love when Unity puts this in their example scripts..
I'm curious now, what does UpdateMaterial do?
What is not performant
I haven't really checked, what kinda overhead does changing material properties have
void UpdateMaterial()
{
switch (m_Server.currentIngredientType.Value)
{
case IngredientType.Blue:
m_ColorMesh.material = m_BlueMaterial;
break;
case IngredientType.Red:
m_ColorMesh.material = m_RedMaterial;
break;
case IngredientType.Purple:
m_ColorMesh.material = m_PurpleMaterial;
break;
}
}```
not sure why they don't just use an event 🤔
I think it's not performant because instead of sharedMaterial it uses material which instantiates a new material IIRC
just odd doing it every frame when it can just be when m_Server.currentIngredientType.Value changed
they literally have an event for that xD
wish they wrote in comment why they did it that way..just laziness or wat..
yes i would like to do this, but since i cannot ever anticipate note density (the amount of notes on the screen at a certain moment in time), I could run out of objects if there are too many for pooling to keep up with. maybe. probably.
the pool should grow dynamically if you need more objects
AssetDatabase.onImportPackageItemsCompleted
I use this callback when execute AssetDatabase.ImportPackage(package, false);
everything works well for simple packages, but when I tried to import the FacebookSDK or Firebase package, for some reason this event simply does not get called... Can someone tell me why this is happening?
if there are no nodes left in the pool you create a new one, it's as simple as that
Hey there, I wanted to ask if it is possible to draw a prefab or something using either gizmos or similar techniques, i need to preview some motion that needs to be accurate displaying a referenced gameobject
I have tried instantiating during gizmos but I do not know if it's possible to know when an object has been deselected in order for the prefab to disappear and prevent clones, and keeping the hierarchy clean
Good evening everyone
Auto-importing packages from code
I ran into a small problem that is a little annoying
This means I import packages through code like this
AssetDatabase.ImportPackage(package, false);
Unity has the following events
AssetDatabase.onImportPackageItemsCompleted += OnImportPackageItemsCompleted;
AssetDatabase.importPackageStarted += name => Debug.Log($"importPackageStarted : {name}");
AssetDatabase.importPackageCancelled += name => Debug.Log($"importPackageCancelled : {name}");
AssetDatabase.importPackageCompleted += name => Debug.Log($"importPackageCompleted : {name}");
AssetDatabase.importPackageFailed += (name, message) => Debug.Log($"importPackageFailed : name: {name} message : {message}");
The crux of the problem is this
If I import some simple packages with several files, then everything works as expected for callbacks, they are called as in the screenshot (screen 1)
But if I take some package from Facebook or Firebase, then the callbacks are like this, and the Complete callback is not called at all (screen 2)
Does anyone have an idea why this could be?
it's better to use Gizmos.DrawMesh with some of the meshes from your prefab
it is a hierarchy of quite a lot of meshes and empty game objects acting as joints
but well if there's no other choice i'll do that
yeah so it goes. it's going to be easier this way
if you want to visualize in the scene view
You can set Gizmos.matrix to a matrix with the preview's position and rotation
And then draw the child meshes with their localPosition and localRotation
Might be more complex if your children are nested
In any case set the matrix and then draw them with positions/rotations/scales relative to the parent
!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 all! Just wanted to ask a quick question in here -- i'm currently working with Editor scripting in Unity for the first time and working on making a better effects system for my game.
The way it works is you can add multiple effects to the list of abstract EffectAction classes. You can add actions like camera shake, playing audio, spawning a particle, etc. For every effect I want to add, I have to add the effect into an enum and use a switch to add the coressponding effect to the list --- which is fine right now but I feel it may get tedious as I continue to add effects. Is there a better way of doing this?
Here's the editor code:
#if UNITY_EDITOR
[CustomEditor(typeof(EffectEvent))]
[CanEditMultipleObjects]
public class EffectEventEditor : Editor
{
public Events eventSelected;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.LabelField("Actions:");
eventSelected = (Events)EditorGUILayout.EnumPopup(eventSelected);
string buttonName = $"Create Action";
if (GUILayout.Button(buttonName))
{
switch(eventSelected)
{
case Events.CameraShake:
(serializedObject.targetObject as EffectEvent).AddAction(new CameraShakeAction());
break;
case Events.PlayAudio:
(serializedObject.targetObject as EffectEvent).AddAction(new PlayAudioAction());
break;
}
}
}
public enum Events
{
CameraShake,
PlayAudio,
SpawnParticle
}
}
#endif```
Any idea if there is any way that the clients that are not hosts of a lobby receive callbacks from LobbyEventCallbacks ?
at the moment only the host receives them
(using the lobby service)
// THIS IS ONLY CALLED ONCE AT THE START OF THE SCRIPT
LobbyEventCallbacks _callbacks = new LobbyEventCallbacks();
ILobbyEvents _lobbyEvents;
private async void SubscribeToCalls()
{
//SUBSCRIBE TO CALL
_callbacks.LobbyChanged += Callbacks_LobbyChanged;
try
{
_lobbyEvents = await Lobbies.Instance.SubscribeToLobbyEventsAsync(curLobby.Id, _callbacks);
}
catch (LobbyServiceException e)
{
Debug.Log(e);
}
}
private void Callbacks_LobbyChanged(ILobbyChanges changes)
{
Debug.Log("Lobby Changed");
//ONLY THE HOST RECEIVES THIS MESSAGE
}
}
https://github.com/mackysoft/Unity-SerializeReferenceExtensions maybe this works better for you instead of using editor scripts
I have a problem with managing my code, I'm making a system where you pick up a object, the placement trigger is activated and when you drop the object in it it activates another object and it destroys those two. Now I'm wondering how i could do this to multiple object and multiple placement triggers in 1 script or maybe if you have another solution i would be happy if you said it. Here are the scripts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpScript : MonoBehaviour
{
[SerializeField] private LayerMask PickupMask;
[SerializeField] private Camera PlayerCam;
[SerializeField] private Transform PickupTarget;
[Space]
[SerializeField] private float PickupRange;
private Rigidbody CurrentObject;
private bool isHoldingObject = false;
public GameObject Placement;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (isHoldingObject)
{
DropObject();
}
else
{
TryPickUpObject();
Placement.SetActive(true);
}
}
}
void TryPickUpObject()
{
if (CurrentObject == null)
{
Ray CameraRay = PlayerCam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0f));
if (Physics.Raycast(CameraRay, out RaycastHit HitInfo, PickupRange, PickupMask))
{
CurrentObject = HitInfo.rigidbody;
if (CurrentObject != null)
{
CurrentObject.useGravity = false;
isHoldingObject = true;
CurrentObject.isKinematic = true; // Prevent physics from affecting the object
CurrentObject.transform.SetParent(PickupTarget); // Set object's parent to the PickupTarget
CurrentObject.transform.localPosition = Vector3.zero; // Set local position to center within the target
CurrentObject.transform.localRotation = Quaternion.identity; // Reset local rotation
}
}
}
}
I removed the drop logic because it was irrelevant and i couldnt send the message
using UnityEngine;
public class PlacementTrigger : MonoBehaviour
{
public GameObject objectToActivate; // Assign the GameObject to activate in the Inspector
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Item"))
{
// Activate the assigned object
if (objectToActivate != null)
{
objectToActivate.SetActive(true);
}
// Destroy the collided item and the trigger
Destroy(other.gameObject);
Destroy(gameObject);
}
}
}
I would gladly hear what you have to say
i think you need array
or queue, though i suggest using array since it is serializable in inspector
when you pick up an object, it needs to search for the corresponding collider to activate
when the collider is triggered, it needs to activate next object
then overlapXXX should work for checking if the drop position is inside the triggered collider
I get the idea but im not going to lie im not very experienced with coding, i understand most of the code but i cant really code a lot myself (i used chatgpt for the code lol), i didnt want to post this in the beginner code channel since this is pretty advanced i think
how do you even get that smart
ive actually been using unity for like 3 years and i havent learned a lot of coding
i guess im going to research what you said to me, thanks for the help
Whats your objective i didnt really understand your problem
You have an object that you place in a trigger and when that trigger detects collision you set an object to active?
im trying to make it that when i pick up an object, the placement trigger where you have to drop the item an item gets activated (a decoration), but i cant figure out how can i do that for multiple game objects i have to pick up
because all of them will be masked under item and tagged item
oh ok yh understood
basically + the object with the item with the trigger only activates when you pick up a object masked "item", that is where the problem arises
Just add a variable to placement trigger of type gameobject and check if other.gameobject is equal to desired object
ig?
the trigger is a cube with a material, box collider on trigger and the placement trigger script
the system works, i just dont know how do i make it work for multiple object and multiple triggers where you have to put the other object
Do a List of gameobjects and check if the List contains other.gameobject
do you mean in the placement trigger script, the other.gameobject is just the item that i have to put in the trigger to activate the game object
Okay let me make an example
Theres a ornament on the floor
i pick it up
the placement trigger object activates