#archived-code-general
1 messages Β· Page 197 of 1
you should 100% report that as a bug
I thought I was going crazy when an enemy performed a 33%-chance attack 30 times in a row
URP 14.0.8 also sets the RNG state, based on frame count
in PostProcessUtils.cs
that's also bad.
shit at that point i'd just start using System.Random to avoid random packages from screwing with the rng
static moment
shame there's no .net 6 yet for that nice convenient Random.Shared
just through the "Report a Bug" window, right?
i'm not sending them my entire project, so I guess I should make a demo
Can't reproduce it in a new project so far. I'll have to embed the package and poke around a bit, I guess
notably, I have no components of type SplineInstantiate in the scene in my game..
Does anyone know how to fix the backround fps of my application? it runs on less than 1 fps and I cant really test stuff in multiplayer. I already checked the NVDIA Control Panel and Player Settings
okay, I can reproduce it now that I actually have it instantiating objects.
This might help https://forum.unity.com/threads/unity-editor-performance-drop-when-losing-window-focus.518761/
I tried that but It didnt work π¦
π Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
We want to make a MonoBehaviour which will have a reference to a system and all the data needed for that syste. For example if it references SceneChangeSystem then it should have a scene's name, if it has a reference to DropThingsSystems then it should have a DropTable. We want it to be only 1 kind of Monobehaviour. It all will be saved to json. We consider the optiong of using uuids as references. Can you think of any way to do something like that?
I'm trying to figure out how to set up VFX. I set up the pipeline and everything. I have a VisualEffect component on one gameobject (prefab). Here is what I am seeing:
- Dragging prefab into scene => yes VFX
- Instantiating prefab programatically => no VFX
Any ideas as to why this is hapenning
Oh my god it wasn't Splines' fault
i mean
Splines is still buggy here. Just reported that issue.
But it wasn't causing the issue.
so i have this pagecollect text object dragged into this script, but when i run my game it disappears???
It's PostProcessUtils.cs in com.unity.render-pipelines.universal@14.0.8
It seeds the RNG with the current frame count
what is causing this?
you're probably reassigning it in Start or Awake
i think i am
i will check
This is breaking RNG for...basically any game that uses URP. Oops.
lol wtf
public class Page : MonoBehaviour
{
public Text PageCollect; // Reference to the Text component
// Start is called before the first frame update
void Start()
{
PageCollect = GetComponent<Text>(); // Get the Text component
}
is the problem here?
yes, remove that line from Start
okay i will try
that's literally reassigning it to the Text component on this object. which does not exist so it assigns null
Hey can anybody help me w a code?
perhaps if you ask a question
thank you so much, it worked, lmao im kinda dumb now that i look at it! thanks!
https://dontasktoask.com/
also see #854851968446365696 for what to include when you do ask a question
Okay so basically how do I separate these 2
Oh okay
Am I in the right chat tho
is it a general code question or a beginner code question? if it is the former, then yes. if the latter then #π»βcode-beginner would be more appropriate
Idk if it counts as beginner
Yk what I'll just ask it in beginner just to be sure
Ty
reported both bugs
very funny how I randomly found a Splines bug by accident
well, that was an annoying two hours, but at least I know what's going on now
Tag: tag name is null or empty.
UnityEngine.StackTraceUtility:ExtractStackTrace ()
ForwardDetector:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Scripts/Enemy/Trigger Checks/ForwardDetector.cs:15)
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag(WallTag) || collision.gameObject.CompareTag(WallTag2))
{
_enemy.forwardDetector = true;
}
else if(collision.gameObject.CompareTag(PlatformTag) )
{
_enemy.forwardDetector = false;
}
}
so apparently if I have a Collider untagged unity gets mad?!?!?
Do the tags have to exist?
or can I not have a tag made thats called "test"
and have WallTag = "test"
ok, cool, but are WallTag or WallTag2 null or empty when you use them?
check by logging them
If WallTag is a public field, then you probably added that field initializer after you already added this component to something
the strings you pass to CompareTag must be not null and not just whitespace. they also have to be an existing tag. the main benefit of using CompareTag is that an error will be thrown when the tag does not exist
the value shown in the inspector is what's serialized
that will overwrite whatever the default value of the field is
gotcha thanks
that was the issue, I just put a random tag in 1 spot cause I just didn't need it and it was throwing errors when I didn't have one π
well no, the error you received is because the string was either null or empty. you'd get a different error if the tag doesn't exist
again, do this.
log both values before that line of code runs
look at what gets printed out
use this line to see both of those tags printed: Debug.Log($"Tags '{WallTag}' and '{WallTag2}'");
okay, but did you do what we both asked you to do?
WallTag2 is null or empty
The conditional short-circuited because CompareTag(WallTag) returned true
Okay but like did you hear that I dont have an error
So it skipped CompareTag(WallTag2)
So they arent null
No, you don't have an error because || short-circuits.
If the first half of the conditional fails, the second half will throw an error when that empty WallTag2 string goes in.
Anyway thx this fixed issue π
yeah until you realize that we were actually right about one of those strings being null or empty
we are trying to get you to understand what actually went wrong
You were originally getting two errors
one for a bogus layer name, one for the layer name being null or empty
(i just went and checked how this would behave)
WallTag2 is still null or empty, but there's no error because || short circuits and prevents CompareTag(WallTag2) from executing
You will suddenly start getting errors again if you bump into something that isn't tagged "wall"
I'm still confused with my VFX issue. I have a prefab with a VisualEffect component. If I drag the prefab into the scene, the VFX plays. If I instantiate it programatically, it does not play, even if I call .Play() on the component.
Removing the component during runtime and adding it back in does nothing.
what about toggling the game object or the component?
also no effect
I had a bug once where I was using GetComponentInChildren<Renderer>() to fetch a mesh renderer
at some point, it started grabbing the visual effect renderer instead
and that wound up breaking the effect
(I was messing with the renderer a fair bit)
doesn't sound like that's what is happening here, though
How to show one object inside another one with Odin?
I did a little more testing. The particles ARE being made. They just aren't rendering
Has anyone done an event heavy version of a their game before?
For me it makes the most sense to do "event storming" (kinda like brainstorming except trying to find events in a software system) and try to find what events occur in what I want to build. I have a tight definition of event to mean "an interesting happening in the game, phrased always in past tense" (YMMV).
Just curious what experiences others have had.
I try to have a few singletons with several very frequently used events, so events can all be coordinated
I also have a bunch of events going around, but a lot of things get tied to something like "OnEnterPlay", "OnLevelLoad"
which then get OnLevelLoadEarly, OnLevelLoad, OnLevelLoadLate so I can orchestrate who does what when
dude this Unity VFX package is garbage. this is the second time the VFX graph file it makes just gets corrupted during normal use, and causes repeated crashes
second time in 1 hour
i saw a unite 2017 video where they used scriptable objects as channels or medium instead of hard rigid reference to classes and i think it's a good method, the problem is that each object that need the SO require a drag and drop from the inspector so i was thinking if DI container is good to inject all so objects
UI ---> PlayerMoney <----- other classes
video link : https://www.youtube.com/watch?v=raQ3iHhE_Kk
Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns. In this talk, Schell Games shares specific examples of how they have used the Scriptable Object for everything from a hierarchical state machine...
I can never remember vector math terms. I suppose this is kind of like project(), but that's not doing that I want.
I have a vector3, say (4, 0, 1) to make it easy. I have a normal (1,0,0), again very simple to make it easy.. What I want is the result of first vector that excludes the normal. So in this case the result should be (0,0,1), because all of the vector magnitude along the normal (1,0,0) has been ignored.
What's the term for this?
if im understanding what you are saying, this isnt some math thing at all. its just a matter of zero'ing out some component
It won't always be zeros
so uh, im attempting to make a 2d game for my friends, and whenever its on office 1 it thinks its on office 2 im new to unity, so i dont exactly know how to fix this
(4,0,1) x (1,0,0) = (4,0,0)
then
(4,0,1) - (4,0,0)
don't know about this not sure i understand u well
@wispy wolf
without completely disabling office 2
I dont believe ive seen such an equation, you may have to elaborate more because ive never heard of "excluding" a normal and ive done a few lin alg courses.
Maybe what GMA posted above is what you want, although you cannot multiply vectors 1x3 * 1x3
you have to multiply each individual component
overlapping ui ?
no, they are in different areas
u need to provide more details so we can help
one second
basically when i try to touch the button for the first office (left) it thinks im on the second office (Right). I have no clue what other details im supposed to give
found out the issue
nvm
i figured out my particle issue. It was caused by orienting to face camera. No idea why that was the culprit.
somehow my game view scales to 1.8x everytime I hit "Play"
Anyone know what's the reason?
do you have Maximize on play enabled ?
nope.
in the resolution dropdown there's a checkbox for "Low Resolution Aspect Ratios". Is that checked or unchecked?
Its unchecked..
it started happening recently. when I added LevelPlay and changed platform to android
Are you using the device simulator?
Or otherwise a mobile device resolution in game tab?
nope. I just set to 16:9 resolution, but it happens in free aspect too.. if I check the low resolution aspect checkbox, my UI adjusts properly. but the lowest scale is then set to 1.8x..
and it looks ugly..
wait now low resolution ratios is checked?
Yes. I just tried with that checkbox ON.. and the UI properly adjusts.. but everything is in low res π
Okay. I think I found a fix.. Unity probably bugged out.. I just changed my editor layout to default and then readjusted all my windows. and it fixed itself.
Thank you for all your help Nashville, Praetor, dlich, navarone ππ»
I didn't help but you are welcome lmao
I've been working on something for a bit and I might be overthinking it and going down wrong paths.
Think of a simple racing game. But instead of being flat the track is round, like a tube, and you are racing down it's length. You don't really turn left or right, you just slide around the tube, always facing parallel to the tube.
Easy enough to make the track -- just spawn some meshes on a spline and bob's your uncle. Gravity will always be toward the center of the spline, so I'll do that myself, but that's pretty easy as well. I can get the tangent of the spline at any given location, so I can even orient the car parallel to the track easily enough.
The problem arises from me wanting to have some level of physics like collisions, jumping off ramps, etc. And that's where the whole thing starts to get tricky.
I don't want to write an entire novel about what I've tried. Any pointers?
Sounds fine aside from gravity towards the center of the tube.π€
Gravity is the easy part, down is always toward the closest spline point and every tick I can add a force.
The part that it tricky is getting the car to follow the track without going nuts on inclines and turns. I can do that easily enough without physics, but I don't want to basically put all the physics stuff back in where I need it
Project on plane.
Vector3.ProjectOnPlane will accomplish that
It's equivalent to projecting onto a vector, then subtracting the result from the original vector.
i.e. foo - Vector3.Project(foo, bar) equals Vector3.ProjectOnPlane(foo, bar)
Would it be easy to make a new base project with a correct render setting, and then just copy the old project files in? if a project is botched for working with specific settings?
In my case, I am unable to get 2D URP shadows working in my project, and I don't know how to properly change the settings. Starting a new 2D URP and the shadows work immediately for me, so it's definitely something project setting specific π¦
I tried making a new Render Asset, and removing all my old ones, reassigning in Graphics & Quality for project settings
You can export your stuff between projects if you want to do it that way, but I can't expect there's much you need to change to get 2D shadows working.
probably some setting you're overlooking
Last time I played around with it, it was an experimental package, but I think it's now just included?
yep, it is definitely strange. setting it up is super fast and easy, as evidenced by my test on a new project....
i have no idea what setting is off in my current project that would stop shadows from being rendered properly
im gonna try cloning my proj into the new one... maybe that will work
I'm trying to like
Me too
yes
The problem with not expressing your thoughts in one message.
lmao me trying to figure out how to phrase it
Then do that first. Then type. Lol
can yall help me tf does this mean π (IM NEW TO UNITY SORRYYY LOL)
get the aspect ratio to be formatted something like "16x9" and not "1.77777..."
and I am going to deep into this I swear, is there any easy way to format the aspect ratio nicely
like some easy function to reduce the fraction to its lowest whole numbers because I couldn't find really anything googling it for unity and without including unity answers are like "install this package"
The first error just tells you that you're including an asset that shouldn't be included in a build. The rest are probably the consequence of the first one.
gotchu
Where do you get the 1.777 from?
Showing the resolution is pretty user friendly, but if it has to be in aspect ration, there must be some formula.π€
I guess you'd have to find the lowest common denominator?
Something like this?
https://stackoverflow.com/questions/13569810/least-common-multiple
yea I think im just gonna have to incorporate my own function
I was just hoping there was like some built in function or easy algorithm
Iβm a bit confused as to why a little code block I have costs a lot of computation time. What I do is:
- Get the corners of the bounds of a collider as vector2s
- Convert the vector2 to vector2int using Grid WorldToCell to get cell coordinates.
- Loop from the min and max on x and y to make an array of all cell coordinates that the square collider touches.
This doesnβt seem like itβd be expensive, but 50 calls per fixed update really hurts my frame rate, and I donβt understand why.
and each array is usually 4 entries large
The light just wasn't bright enough to make a shadow... LOL
or maybe my bulb was too dim
π
What do you see in the profiler?
I HAVE NO IDEA WHAT THE [Redacted] I DID BUT MY BUILD WORKED π€π€π€π₯
Deep profiler says that that function is only getting called like 40-50 times a frame, but taking like 11-20 ms or some shit. Itβs ridiculous. And when I look into the breakdown, itβs split evenly across a bunch of casts and vector operations
Can you share the data?
Sounds like you're just doing a ton of stuff
i can share tomorrow when I can get it again
each one call is maybe like 20 very basic vector operations
x40-50 per fixed frame
found the solution but im gonna have to filter them anyways bc I get bs like 903x509
because something of a supported resolution is that aspect ratio
may just make a "Other" category and put resolutions that dont past the filter in there 
I get a null pointer exception when colliding bullet with enemy. I have a takedamage function in my health script, but it doesn't seem to be able to find the Image I have that is used for the healthbar when it is called from an OnTriggerEnter2D function in my bullet script. However, in my health script, I also have an Input.getKeyDown function that also runs the same TakeDamage() function. Using that, unity seems to be able to find my health bar and update it appropiately.
this is in my bullet script
this is in my health script.
Start does show the healthbar in the console
and healthamount updates appropiately
I am confused as to why the TakeDamage() function seems to see the healthamount variable, but not the image variable.
Both are declared: public Image healthbar;
public float healthAmount = 100;
Can you show the console error from the Unity editor?
instead of catching it?
you just want the error
What line is 41 of the health script?
It's a message rather than an error so I'm guessing the health bar is null if not caught
Where do you assign health bar?
I declared it at the top of health.cs if thats what u mean
Is this a spawned object?
The object with the health isn't a spawned object though correct?
no
So, there's a high possibility that the health bar you've referenced isn't one in the scene
possibly
but my confusion comes from the fact that i can refrence that healthbar from inside the health script
So I changed my project's build target to Android, and now my TMP text appears as pink squares (in the editor, it's fine in the build for some reason). Any idea what's happening here? I tried deleting the package cache and letting it all be re-downloaded (someone said refreshing that stuff should fix it), but that didn't work.
Thoughts?
but cant seem to access it when outside of the script
but i can access the healthamt float just fine
Log the name of the object that was hurtcs Debug.Log($"{name} took {damage} damage");
in my take damage func?
Yes
Did you try deleting the library folder?
no I didn't
so I presume there'll just be a bit of a loading screen while it reinstalls everything?
Debug.Log($"{name} took {damage} damage", this);
Debug.Break();//Pauses the Editor```Edited
The editor would need to reimport assets the next time you open it.
you want me to include the this?
Of course - replacing the previous
yeah that's what i figured
i did comment out the healthbar.fillAmount = health / 100
After the game is paused, select the message and see which object is highlighted yellow from the hierarchy. Check the component on that object.
cheers thanks mate
No need to, just log before that line
.
Does it have the health bar reference in it's health bar setup?
Apparently it's expected to have health
so your saying i should declare healthbar in the bullet script?
No, I'm saying whatever that's trying to lose health doesn't have the health bar reference. Since you're logging this in Health, it would show what's being damaged and pause the game for you to verify that it's got a proper reference.
I'm assuming you've done this logging in Damage and the object damage was the bullet.
Where the bullet had a health script and a health bar
But threw an error because the bar wasn't set up - obviously not correct.
The highlighted object should be an object with the health script
Show the damage method
Logging should be done here
Where the log should be this.
Verify that the highlighted object has an appropriate script and referenced field when paused.
I'm assuming the field is empty/missing/none etc
Looks correct
Check it's component and field. The game should have paused after the break message.
Okay, fixed it. The Health Script in my Enemy prefab didnt have the healthbarimage attached to in it's components
Thanks a lot man
This is my first time in unity so I probhably overlook a lot of things
A small stepping stone. You'll be fine π
Before you continue, please properly configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
It is currently not properly configured and will not be able to provide the basic help an editor should give you
public async void LoadTexture2(string fileName, string subFolderName, RawImage image)
{
Texture2D tex = null;
UnityWebRequest www = new UnityWebRequest(GetStorageUrl() + subFolderName + "_" + fileName + "_persp.png");
www.downloadHandler = new DownloadHandlerBuffer();
await www.SendWebRequest();
while (!www.isDone) await Task.Yield();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
// Show results as text
Debug.Log(www.downloadHandler.text);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
tex = new Texture2D(100, 100);
tex.LoadImage(results);
image.texture = tex;
}
}
Hello
can someone tell me if there is something wrong with my code?
this code is for downloading a png file from firebase storage as texture then set a raw image's texture with it
the code works until the end but the texture that is attached to the raw image does'nt show anything or blank
there is no problem with the link because i can view the image normally
and the debug result for the download handler text is like this
tried to use downloadhandlertexture previously instead of buffer but return a null instead
Can you declare tex as a class field and check it in the inspector? I also wonder if you need to use .Apply after loading the data.
It could also because you're using obsolete API.
Try this instead:
https://docs.unity3d.com/ScriptReference/ImageConversion.LoadImage.html
can somebody help me? my map is slowly moving upwards
if i use apply it become like this for firebase link
but for another link it loaded normally
oh ok now i just found the problem
what a silly mistake
for firebase storage link
i need to add "?alt=media" at the end of the link for it to be working
damn
at least i can sleep peacefully now
Hello everyone, i am encountering this error in Unity 2021.3.27. It always appears 11-times after a Domain Reload
Do you guys know how to fix it ? if it can be fixed.
I found that somebody recommended disabling lights in scene view, but thats not working for me.
What am I doing wrong?
public class PlayerSonar : NetworkBehaviour
{
[SerializeField]
Player player;
public List<Transform> enemyList = new List<Transform>();
private void Awake()
{
player = GetComponentInParent<Player>();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player") || other.CompareTag("Enemy"))
{
player.enemyList.Add(other.transform.parent.transform);
enemyList.Add(other.transform.parent.transform);
}
}
I can see enemyList being update in current script but not on Player script
Loop
That just says that some handle was not released properly before domain reload. Maybe looking at other errors/warnings/messages can give a clue.π€
Something must be modifying the list after you add to it.π€
Or you're looking at the wrong object.
how
I have only one Player object
Loop an array of floats/ints and assign a random value.
Then it's the other option.
Anyways, stepping with a debugger, should reveal some more clues.
I am not sure how to debug since the script is as above and the Player script is just this:
public class Player : NetworkBehaviour
{
public List<Transform> enemyList = new List<Transform>();
}```
With a breakpoint, you can check the fields/properties of the referenced object.
But here's one thing to check first: is player a reference to a prefab or an object in the scene?
Also, networking might be making things a lot more complicated...
prefab that is created when client join the server
So it's not the same object that you're looking at
You're looking at the instance of this prefab in the scene.
but when press the Inspector script, I can see the parent object being selected
Also, "prefab that is created" - is incorrect. An instance of the prefab is being created. Not the prefab itself.
Take a screenshot.
Ah, wait. You said it's a parent?
yes
since:
[SerializeField]
Player player;
public List<Transform> enemyList = new List<Transform>();
private void Awake()
{
player = GetComponentInParent<Player>();
}```
I blindly dove into your code too, but it seemed like it should be working. Sometimes it's good to take a step back x)
indeed, ty!
I have this blend tree which I use to cycle between random 'bored' animations. I control it using a StateMachineBehaviour script.
It it possible to get the number of motions in this blendtree without directly setting the data as an inspector value? If I were to add an animation cycle to this tree, but would forget to change the inspector value, the animation would never play. I'd preffer to set it programatically but getting to the blendtree seems like a bit of a challenge.
It's not impossible in the editor. Look at the animator API in the editor namespace. You can get the specific state and the blend tree info.
Heya! Im trying to do a certain action in OnTriggerEnter2D, but only when the collission is happening with a certain layermask, but i cant quite figure out how?
I tried to do this
basically comparing the layermask, and the object's layer
but it doesnt exactly work, probably because im comparing a single layer to a layermask
Here is a little helper struct I made.
The method MaskHasId is the one you need
Omg, thanks!
i have an issue using the tank example from unity with scriptable. Project is working, but for example, i have an scriptable "decision" that search for the player and return true if i can see the player and change state to chase, the problem is when there is alot of enemies and all of them using same scriptable, when one enemy in player range return true, its true also for other enemies, so each enemie have to use a different scriptable "decision" or "action"?
so, an state cannot share actions or decision made it with scriptable right?
probably the easiest solution is to use ScriptableObject.CreateInstance to create a local instance of your SO, then write a Clone method to copy the data from the SO Asset into the local instance
That way each tank has their own SO instance to work with
Usually you use SOs as immutable data and unload it onto an identical class and instead create instances of those, otherwise you'll have to be careful not to write to the original SO data when creating instances of it.
not going to happen, an instance of an SO is not an asset until it is Created in the Editor. In runtime this is not even possible
I recall some funky stuff happening when writing to SOs at runtime, which usually required restarting the editor to serialize data again. What's the difference between using createinstances and instantiating them?
To start with you cannot instantiate a SO, like a MonoBehaviour you cannot use new().
writing to SO's at runtime will not persist data (outside of Play Mode in the Editor) so you have to be careful.
This is why I made
https://assetstore.unity.com/packages/tools/utilities/scriptableobject-pro-218340
which handles making SO's persistent at runtime and also allows runtime created SO's to be persistent
Oh, huh. I thought you could instantiate them. I remember reading some argument about which was better to use but that was earlier on when I've not dabbled with them much.
no, only CreateInstance is allowed
Instantiate can clone any UnityEngine.Object, including ScriptableObject. But if you want to create one from scratch, CreateInstance is your only option.
you can use Instantiate for scriptable objects. the catch for that is that you already need an instance though because it clones it
ok so maybe that was my problem
Good point, I had not thought about instantiate, question is is that a deep or shallow copy?
but if createinstance makes an identical asset, that makes much more sense to use
Instantiate is a shallow copy. References aren't cloned, though serialized classes are, since Unity's serializer treats those as value types. I'm not sure how [SerializeReference] fields are copied.
Shallow copy would work for the question asked as long as he is only using primitives
Be interesting to see if an Instantiated SO is still linked to the original Asset though
because by using CreateInstance you are breaking that link
Sorry, I read that as instancing rather than instantiating
@copper rose I think for you this should work
public MySO originalSO; // Set in inspector
MySO localSO;
...
void Awake() {
localSO = Instantiate(originalSO);
}
There after just use localSO
Every time BuyTroop is called from any button, buySlot is equal to buySlots.Length, causing an out of bounds error. This is probably a dumb oversight by me, but I really don't know what it is.
public void BuyTroop(int buySlot){
Debug.Log(buySlot); //Always outputs buySlots.Length
NPCObject npc = buySlotTroops[buySlot]; //This has the same length as buySlots, so this is erroring
if(npc.cost > money) return;
//...
}
private void BuySlotButtonsSetup(){
for(int i = 0; i < buySlots.Length; i++){
//buySlots[i].GetComponent<Button>().onClick.AddListener(delegate{BuyTroop(i);}); //Suggested answer
buySlots[i].GetComponent<Button>().onClick.AddListener(() => {BuyTroop(i);}); //Suggested answer
}
}
None of the buttons have onClicked on anything in the editor, so nothing should be interfering with this, But I did try with giving each of the buttons an onClicked in the editor with "No Function", but surprise surprise, that didn't work. What works tho is if I set the onClicked in the editor to call BuyTroop(n);
The "Suggested answers" mean answers to what I am trying to achieve in https://discussions.unity.com/t/button-onclick-addlistener-how-to-pass-parameter-or-get-which-button-was-clicked-in-handler-method/179151/2
Try this : void Start () { ButtonPre.onClick.AddListener(delegate{SwitchButtonHandler(0);}); ButtonNext.onClick.AddListener(delegate{SwitchButtonHandler(1);}); } void SwitchButtonHandler(int idx_) { //Here i want to know which button was Clicked. //or how to pass a param through addList...
try
private void BuySlotButtonsSetup(){
for(int i = 0; i < buySlots.Length; i++){
//buySlots[i].GetComponent<Button>().onClick.AddListener(delegate{BuyTroop(i);}); //Suggested answer
int x = i;
buySlots[i].GetComponent<Button>().onClick.AddListener(() => {BuyTroop(x);}); //Suggested answer
}
}
That.. works
But I am very confused
Thanks tho
The problem is that
BuyTroop(i)
is evaluated at call time
and at call time i == buySlots.Length
by using x it creates a unique variable for each call
If you really want to know https://unity.huh.how/programming/specifics/anonymous-methods-and-closures
Ill just quietly delete that in shame π€«
if (HasReadScripts[d.HasWonKey])
{
}
if I haven't actually set HasReadScripts[d.HasWonKey] to anything, will it throw an effor or just presume it false
(HasReadScripts is a Dictionary<string, bool>)
If you just want to check use the ContainsKey method
yeah
how can I check if an object is a certain class?
Like if I need to iterate through a list of Item can I check if the current item is a Drink that derives from Item
foreach (Item item in allitems) {
if (item is Drink d) {
d.Spill();
}
}```
I would say in general it's not recommended to do this if you can avoid it though
yeah, it indicates you have a design problem
oh noees
Thanks
Although, this does feel unavoidable when making inventories.
yeah
you have a bag of Item and you also need to do specific things with specific kinds of items
I guess you can keep separate lists of each kind of item.
ideally you do something more like:
foreach (Item item in allitems) {
item.Use();
}```
And let the item itself decide what "Use" does through polymorphism.
well yeah I do already do that
however I need to keep track of whether or not the player has read a book
I will test this later
sounds like the book's job.
in the "Use" function for the book, set the "Player has read a book" flag
you underestimate my ability to poorly make inventories
But right now I donβt know why could be better to use so for my states of each enemy
well, here's a chance to improve the system (:
yeah
rn I have a dict of strings containing the book's name and whether or not the player has read it
yeah why not set this in the book class
ig on the book's end I can check if the player has read it
im stupid yeah
if (!playerStats.GetComponent<Inventory>().HasReadScripts.ContainsKey(HasWonKey))
{
playerStats.GetComponent<Inventory>().HasReadScripts[HasWonKey] = false;
}
else
{
if (playerStats.GetComponent<Inventory>().HasReadScripts[HasWonKey])
{
HasWon = true;
}
}
(ignore the use of getcomponent, ill fix it later)
public enum BulletTypes
{
FireBall=0
}```
is there a way to rename Fireball without destroying every SO that has a SerializedField of BulletTypes?
noticed when I renamed enum "items" in the past it basically "wiped" all my SOs
in visual studio you can highlight it and hit ctrl-r-r and then that renames all instances
but I might not know what an SO is and this wont work at all
Enums are serialized by value.
so if you have FireBall selected in a dropdown, Unity is serializing 0
if you update this to
public enum BulletTypes
{
IceBall = 0
}
then every place that used to say "FireBall" will now say "IceBall"
because that's now the name for the 0 value
awesome thanks...so when I dont have the = 0 part and just have names is when it "breaks"
In this case, it still wouldn't break
By default, enum values are numbered starting from zero
public enum BulletTypes
{
Foo = 0,
Bar = 1,
Baz = 2
}
This is equivalent to not specifying the values.
public enum BulletTypes
{
FireBall,
ball1,
ball2
}```
in the past I've renamed like ball2->test
it's more about when the name and the value become decoupled. Changing:
public enum BulletTypes
{
FireBall=0,
IceBall=1
}``` to
```cs
public enum BulletTypes
{
FireBall,
IceBall
}```
wouldn't break it but:
```cs
public enum BulletTypes
{
MeatBall,
FireBall,
IceBall
}``` would break it.
you could avoid that by doing
public enum BulletTypes
{
MeatBall = 2,
FireBall = 0,
IceBall = 1
}
because now FireBall and IceBall have different values than they did before
note how the values aren't changing, since we gave explicit values
This is also incredibly aesthetically displeasing
I hate it
gotcha
welll a normal person would add MeatBall at the end
it's when you start removing old stuff that it gets bad
it's also clearly the most powerful bullet type and should have the highest value π
public enum BulletTypes
{
MeatBall,
FireBall,
IceBall
}```
->
```cs
public enum BulletTypes
{
MeatBall,
FireBall2,
IceBall
}```
in this case would "renaming" fireball ->fireball2 work?
It would work fine assuming your goal is to change all existing "fireball"s to fireball2s
sweet thanks
This is an option.
public enum BulletTypes
{
[Obsolete] MeatBall,
FireBall,
IceBall
}
if there are scripts in a prefab, does the prefab run them?
When it is instantiated, yes.
That's why I clarified when instantiated. Before that, no.
There IS code to make things run in the editor. But without explicitly specifying, no it does not
Prefabs are in a kind of weird state. IIRC they have no parent, yet activeInHierarchy is always false
ok I have solved the issue: I'm just crazy
public class Bullet : MonoBehaviour
{
[SerializeField] protected float speed = 15f;
int dmg = 3;
string shooterTag = "";
IObjectPool<Bullet> pool;
public EffectTypes effectType;
public BulletTypes bulletType;
Rigidbody2D _rb;
private void Start()
{
SceneManager.sceneLoaded += SceneChange;
_rb = gameObject.GetComponent<Rigidbody2D>();
}
....
if(_rb == null)
{
Debug.Log("rb null");
}```
while im here I'll just doublecheck
public float Rarity;
// Start is called before the first frame update
void Start()
{
var rand = Random.Range(0, maxInclusive:100.1f);
if(rand < Rarity)
{
Destroy(gameObject);
}
}
this works reasonably well for a structure rarity script right?
why is it throwing rb=null?
its cool
its very long so tried to just give important piece π
i can handle it
use pastebin or something like that, to avoid filling the chat
There may be important context.
Do you instantiate the bullet and then instantly fire it?
Start runs before the first Update
which happens on the next frame
hm?
var chance = Random.value; if(chance <= 0.5f) // 50% chance
Do your work in Awake
Awake runs instantly after instantiation (before the method returns) as long as the component is on an active gameobject and is enabled
didn't know that was a thing
you'd just want to use 100f, not 100.1f, if you were going to have a rarity value be between 0 and 100
but that shouldn't run until "fire" is called
cool
maxexclusive threw me off
value goes 0-1
yeah
same as 0-100
I have no idea why they thought it should default to exclusive
true
ah
I'd prefer it to be exclusive
if you use < for a chance, then 100% (1) can still fail
and if you use <=, then 0% (0) can succeed
System.Random.NextSingle() is exclusive
public class Bullet : MonoBehaviour
{
[SerializeField] protected float speed = 15f;
int dmg = 3;
string shooterTag = "";
IObjectPool<Bullet> pool;
public EffectTypes effectType;
public BulletTypes bulletType;
Rigidbody2D _rb;
bool fired=false;
public class WeaponAttack
{
[SerializeField] private Rigidbody2D FireballPrefab;
BulletTypes bulletTypes;
MyWeaponType weaponType;
AttackType attackType;
Fighter fighter;
public WeaponAttack(MyWeaponType weaponType, AttackType attackType, Fighter fighter = null)
{
this.weaponType = weaponType;
this.attackType = attackType;
this.fighter = fighter;
if(FireballPrefab != null)
{
bulletTypes = FireballPrefab.GetComponent<Bullet>().bulletType;
}
}```
Debug.Log(bulletTypes);
this should be outputting "Curving Away" right?
well, I don't know where you're actually logging that
if you log it after calling WeaponAttack, then probably
Its being logged inside of WeaponAttack when the weapon fires
not in that code you shared.
please don't try to trim things down for us. just share the entire script.
it's a lot harder to help you when you've removed (very important!) parts of the code
which is called from DoAttacksAndTimer() inside of
which has this bullet serialized
inside this object
the top WeaponAttack code is debugging "Straight"
oh, I see what you're doing
that's a constructor.
constructors are run before serialized values are restored
Running debug in the window shows this
not sure how its not getting my Fireball Prefab at all
since its serialized here
oh...when I call
weaponAttack = new(weaponType, attackType, enemy);
that wipes out my serialized prefab doesnt it
that's creating an entirely new instance of your WeaponAttack class
it's not even wiping it out
the reference was never there at all
dang, thanks π
Its always something dumb I do
I need to serialize that and pass it through constructor instead
i never understand when a class can be serialze, i use it for private values to assign throw inspector, but a class serializable is when dont use update and is like an scritable object to store methods?
maybe this is for beginner lol
if you make a class and put like Serializable on the top you can serialize it
having an Update method has nothing to do with being serializable
A class is serializable if it can be converted to data and recreated from data.
like an scriptableobject?
yes
ok thanks, i never use this in my clases now i think i understand
I am a little rusty on the exact terms.
Unity handles UnityEngine.Object-derived classes specially. They aren't serialized in-place. You just drag in a reference to the object from somewhere else
If you have a regular class (not derived from MonoBehaviour, ScriptableObject, etc.) that's marked as serializable, it'll get serialized in-place in the inspector
so you just see the values right there
ok thanks so much for explain this
My player object has a sphere collider of radius 300.
How can I make that only other player object that are within that sphere will receive NetworkVariables? (for example HP of player 1 will only be sent to Player 2 when they are close)
You could check whether player 2 is close enough to player 1 with (player1.position-player2.position).sqrMagnitude < 300*300
or with (player1.position-player2.position).magnitude < 300 if you want
so you're trying to implement relevancy?
Relevancy, or scope, indicates if the object or data is important to you. it's often used as part of systems that deal with the realities of limited bandwidth.
but how to actually hide player 2 from player 1?
(just some terms that might be useful to know)
ah, ty
please do not spam
cute but there is no offtopic
{
if (button.GetComponent<TMP_Text>().text == DesiredWord.text)
{
score++;
ScoreDisplay.text = score.ToString();
}
NextQuestion();
}```
``` foreach (Button button in Options)
{
button.onClick.AddListener(() => AnswerCheck(button));
}```
causes null exception. assumably having an anonymous lambda here is bad and what causes the issues. is there another efficent way to pass button through into say TaskOnClick() or some other method?
(personal project)
omg unity staff i'm a big fan with unity staffs
Capturing the foreach variable should be fine.
You only get bitten if the variable survives from iteration to iteration
like capturing i in a for (int i = 0; i < whatever; ++i) loop
Where is the NRE coming from?
(don't buttons usually have the text as a child of the button?)
yeah, that's probably your issue
oh yeah! i forgot to use "GetComponentInChildren" smh
I would create an "Answer Button" component that holds the references for you
thank you <3
no prob
GetComponentInChildren has burned me in the past when I started adding more components to a hierarchy
So I need a little help. My brain does not brain.
I would like to calculate the rotation of the rigidbody on which the camera looks it needs to look to the red cross.
The blue arrow is the direction vector from the camera to the humanoid:
Vector3 cameraToTargetDirection = unitMainManager.transform.position - mainCamera.transform.position;
cameraToTargetDirection.y = 0;
return cameraToTargetDirection.normalized;
The red cross is the input from the player in this case Vector2(1,0).
Would be nice if someone could help briefly.
This is the code that i got atm.
public void RotateUnitPlayer(float rotationSpeed, Vector3 cameraLookAtDirectionVector)
{
if (!unitLocomotionHandler.AcceptRotationInput || unitLocomotionHandler.MovementInput.magnitude == 0)
{
return;
}
// Calculate the target rotation based on the movement input and the camera look-at direction vector
Vector3 movementInput = new Vector3(unitLocomotionHandler.MovementInput.x, 0, unitLocomotionHandler.MovementInput.y);
Quaternion targetRotation = Quaternion.LookRotation(Vector3.Scale(cameraLookAtDirectionVector, movementInput));
// Smoothly interpolate between the current rotation and the target rotation
Quaternion newRotation = Quaternion.Slerp(rigidbody.rotation, targetRotation, rotationSpeed * Time.deltaTime);
rigidbody.MoveRotation(newRotation);
}
If you need to turn player input into a camera-relative direction, just do this
Vector2 playerInput = ...
Vector3 moveInput = new Vector3(playerInput.x, 0, playerInput.y);
moveInput = Camera.main.transform.TransformDirection(moveInput);
Now you have a direction from the perspective of the camera
You will probably then want to throw out the vertical component
Intial speed is
_rb.velocity = transform.right * speed * 0.5f;
Is there a good way to speed up each frame in fixedupdate? running into a bit of issues because I need it to always move "transform.right"
float length = moveInput.magnitude;
moveInput = Vector3.ProjectOnPlane(moveInput, Vector3.up);
moveInput = moveInput.normalized * length;
ahhh omg let me test it quick 
We need to restore the original length of the vector after doing this
since we'll lose some magnitude
Then, you can just do Quaternion.LookRotation(moveInput) to get a rotation
This is only necessary if the camera is pointing up or down. But, cameras tend to do that!
so you want to accelerate?
store the current speed and add to it every fixed update
speed += Time.deltaTime * acceleration;
_rb.velocity = transform.right * speed;
Time.deltaTime and Time.fixedDeltaTime are equal while in FixedUpdate, btw
thank you very very much!
do you got ko-fi or so?
i did but i linked it to a nsfw twitter account and they got mad
lmao
thanks for offering, though :p
gotcha, I was thinking of trying to do something like this π
Using the methods on Transform can make your life a lot easier
ah damn - wanted to show some grattitude
float currentSpeed = _rb.velocity.magnitude;
_rb.velocity = transform.right * currentSpeed *speedIncreaseRate * Time.deltaTime;
this would be expoenntial
well, it'd probably go to zero, because you're multiplied in Time.deltaTime
yeah it just sat and did nothing π
this multiplies the current speed by a speed increase rate, then divides it by the framerate
very wonky
If you want the speed to increase at a constant rate, add a constant amount to it each fixed update
gotcha thanks, your way is much easier to use and configure π
(this would either go to zero or go to infinity very quickly)
depending on whether speedIncreaseRate was below or above 50, given the default physics timestep of 0.02
oh thats so weird
most of my projectiles hit the ground and die like they are supposed to
but 1 random one goes through the ground before "dying"
If they're moving very quickly and the ground is very thin, they could be missing the ground entirely
hmm true
I have a tilemap collider and composite collider for the sides and floor
Collision Detection is set to Continous though so wouldnt expect the speed to matter
Hey! I have a question. Are the M1 iMacs good for Game Dev?
you should ask this in #π»βunity-talk
StartCoroutine(DestroyAfterDelay(5f));
is this the correct way to "stop" it if I need to?
StopCoroutine(DestroyAfterDelay(5f));
No
You must store the Coroutine that's returned by StartCoroutine.
That is an option, sure
if you wanted to stop all coroutines
(on that MonoBehaviour)
StartCoroutine is a method on MonoBehaviour that takes an IEnumerator. The MonoBehaviour throws that enumerator into a big list of things it's running.
So passing StopCoroutine the result of DestroyAfterDelay(5f) wouldn't do anything, because it's never seen that particular enumerator
you can do this
var myEnumerator = DestroyAfterDelay(5f);
StartCoroutine(myEnumerator);
StopCoroutine(myEnumerator);
but I don't see a particular reason to do that
storing the Coroutine is easier
Hello! I'm trying to do this kind of thing in a 3D bomberman prototype cloning and i'm really struggling to get this right.
I've researched some ways to do it and the best result I have is using rigidbody velocity and applying it (using the target as a parameters), the problem is, using physics you can't really control the velocity of the bomb throw by time and I think it's one of crucial things to get a good game feel.
Do anyone have a suggestion on what I could do to achieve this kind of behaviour?
I do not understand what you're trying to do
Are you talking about making the bomb fly further if you're moving in the direction you throw it?
using physics you can't really control the velocity of the bomb throw by time
Pretty sure you can
You do not use Physics for that.
if he wants the player to be able to run into the bomb to push it he might want physics
Not for the movement. You would just activate a collider at the right moment.
You do not need physics as a rigidbody for the movement.
I still don't know what the question actually is.
If he wants to collider and push the bomb that would require physics?
same π
InvalidOperationException: Trying to release an object that has already been released to the pool.
UnityEngine.Pool.ObjectPool`1[T].Release (T element) (at <f7bcd9bfa40c4821acdda68a85850616>:0)
Bullet.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/interactable/Bullet.cs:38)
Is there a way to fix this error by checking if its already been released?
idk how it could happen anyway
but it annoys me
funny .. was working on the same type of game but in 3D lol (bad lag my laptop sucks rn)
void OnTriggerEnter2D(Collider2D collision)
{
var tag = collision.transform.tag;
if ((tag == "Fighter" || tag == "Player") && tag != shooterTag)
{
Fighter colFighter = collision.GetComponent<Fighter>();
colFighter.Damage(dmg);
//Debug.Log("Pool Release called");
fired = false;
StopDestroyAfterDelay();
pool.Release(this);
}
else if (tag == "Wall" || tag == "Floor")
{
fired = false;
StopDestroyAfterDelay();
pool.Release(this);
}
}
Not necessary. Also, I would not use physics in such environment.
line38 is the first pool.Release(this)
now Im wondering if I should be using physics π
π
Ive just got a 2d platformer runner/gunner type game
how?
yes after like 6 hours i figured it out
speed += Time.deltaTime * speedIncreaseRate;
_rb.velocity = transform.right * speed;```
that changed my bullets velocity
the thing is
i want to reach a specific target
a grid cell
if I change the velocity
i will miss the target
I mean...once it hits the cell put the velocity to 0?
You can calculate the required velocity to get to a target though.
but the movement is a parabola
If you don't predict the velocity you need, you will miss, not if you change the velocity
with fixed height
in bomberman, the bomb always go in the same speed/height and land on the same spot (i think 4 grids away or 3)
You need calculations that will apply a specific velocity so the bomb will land 1-2-3-... cells away
For 3D:
private void SolveForVelocity(Vector3 startPosition, Vector3 endPosition, float gravity, float angle, out Vector3 velocity)
{
//x = v * t
//x = v * cos(a) * t
//h = v * sin(a) * t + 1 / 2 * g * t ^ 2
//t = x / (cos(a) * v)
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) ^ 2
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * (x / (cos(a) * v)) * (x / (cos(a) * v))
//h = v * sin(a) * (x / (cos(a) * v)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//h = sin(a) * (x / cos(a)) + 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//h - sin(a) * (x / cos(a)) = 1 / 2 * g * x ^ 2 / (cos(a) ^ 2 * v ^ 2)
//1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) = cos(a) ^ 2 * v ^ 2
//1 / 2 * g * x ^ 2 / (h - sin(a) * (x / cos(a))) / cos(a) ^ 2 = v ^ 2
Vector3 delta = endPosition - startPosition;
float x = Mathf.Sqrt(delta.x * delta.x + delta.z * delta.z);
float x2 = x * x;
float h = delta.y;
float g = gravity;
float sin = Mathf.Sin(Mathf.Deg2Rad * angle);
float sin2 = sin * sin;
float cos = Mathf.Cos(Mathf.Deg2Rad * angle);
float cos2 = cos * cos;
float r = Mathf.Sqrt((0.5f * g * x2) / (h * cos2 - sin * x * cos));
Vector2 planeDirection = new Vector3(Mathf.Cos(Mathf.Deg2Rad * angle), Mathf.Sin(Mathf.Deg2Rad * angle));
Vector3 direction = new Vector3(delta.x, 0, delta.z).normalized * planeDirection.x + Vector3.up * planeDirection.y;
velocity = direction * r;
}
Which would be probably the best and easiest
ty i will try it later when i finish my job
yes actually
this is what I want to do now
so i can probably control the movement duration
and make things more on control
and also avoid akward behaviours
now Im confused on when to use rb/physics and when not to π
i think you only use physics when you will need
in this case, i don't think its necessary because I want the thing to move from A to B in a curve
it doesnt really matter how
It depends on what you do and what you want.
it feels weird to mix physics and non-physics objects to me
take like a 2d platformer game where you shoot bullets at an enemy
gravity on enemies is nice
Β―_(γ)_/Β―
You do not need to have your RB as simulated though.
yep, but the bullets doesnt need to be physics based
they could be a simple translate
In fact, most of the time only non important object are simulated. The rest would be Kinematic.
why?
wouldn't have like...gravity be nice?
You do it yourself.
aka just change from body type dynamic->kinematic?
Rigidbodies are necessary to get collision events
For non-physical objects, you can use a kinematic rigidbody
can you still use like rb.velocity with a kinematic rb?
or do you just have to use translate
You have to move the rigidbody with MovePosition
Directly moving the transform will mess up the physics events.
i think 2D is unique in kinematic RBs being able to use velocity
so I would have to calculate how far over I would want to move and make sure no collisions each frame instead of just setting velocity to move?
If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore
but at least for 3D, kinematic RBs ignore velocity
velocity and forces arenβt a thing for kinematic RBs
That's for 3d here is 2d https://docs.unity3d.com/ScriptReference/Rigidbody2D-isKinematic.html
the whole point of a kinematic RB is: you tell it where to go and when, and nothing will stop it from going from point A to point B
so I would just have to program my own collision detection, calculate the position each frame for everything to move and create my own gravity essentially
yeah
yikes
colliders can
that is kind of the point of a kinematic RB tho
The docs has an example:
For example, a human character is usually not implemented using physics but may sometimes be thrown through the air and collide with objects as the result of an impact or explosion.
the doc also says this
If this property is set to true then the rigidbody will stop reacting to collisions and applied forces
kinematic can absolutely be stopped tho
meaning it just ignores colliders no?
thus I need to program my own collidiers to work?
Translation is the one that goes A to B without caring anything
it ignores forces from colliders
kinetic RBs can still hit triggers, and let other things hit them
it ignores external forces but affects others but still collides with colliders
MovePosition still means you can't go through colliders though?
but translation would let you
MovePosition will model the object actually moving from point A to point B
there are just enough differences between the two physics systems to get ya
so imagine mario trying to jump onto a platform that goes in a circle. And the platform goes in that circle come hell or high water, it does not give a fuck about what is in itβs way; it is going in that circle.
Classic case where the platform should be a kinetic RB
thats why when the character doesnt need physics its useful to use kinematic to still get collisions, IE a game where you're like the pong bat
I guess a good question...when should you be using a Dynamic RB
dynamic rigidbodies take in gravity, friction, collision forces, etc
if you want things to run into each other and bounce off?
when you want physics pretty much yea
sounds like you should be using kinematic and just programming your own gravity
a rigidbody participates in the physics simulation
which I would have considered to be physics
a kinematic rigidbody does not respect physics forces
letβs say I want mario to chuck a penguin off a mountain, and I want that penguin to hit every rock, and deflect and slide, and have a nice parabolic arc as it falls into the void. Penguin should be a dynamic RB
a non-kinematic rigidbody does respect physics forces
(i only do 3D, so i'm not familiar with the...static/dynamic/kinematic options in 2D?)
sounds like you should be able to get the same arc just by making a gravity class with a kinematic yeah?
kinematic RBs exist to only do as they are told
I guess static rigidbodies aren't expected to ever move?
yeah. but youβd have to program it
not hard to do. but youβd have to do it
and itβs a lot easier to just make it dynamic, and then it will come with friction, gravity, colliding with walls etcβ¦
well I asked up above and was told that if I just wanted to use Dynamic rb for gravity I just should turn to kinematic and make my own gravity class
pretty sure people just said you can still collide with walls and colliders
kinamtic still collide with walls
you need to program it to ricochet if that is what you want
it will register collision, but wonβt get pushed back
yea
it a good example of kinematic is this
https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131
im setting a bool fron another script true in a different script and im getting the object refrence not set to an instance of an object error does anyone know a fix
so basically physics is if you want friction and "physics bouncing from hitting something or it hitting you"
if you have βOnCollisionEnterβ, it will get called, and that penguin would still keep going straight through that rock until you program it to do otherwjse
not true..
that would be translation
not kinematic, kinematic will stop
the built in character contorller is also kinematic. it is unaffected by physics forces.
although
I dunno if you'd even call it "kinematic", since it's not a rigidbody
kinematic rigidbodies do not respect forces
yeah kinematic and character controller are very similiar
The character controller just has extra logic to detect that it's inside a collider and to correct its position.
a process called depenetration
if you tell a kinematic ball to move in a straight line, it will do that, and will not care if there are any walls are in the way
it will go along that line
you're wrong
if you use Moveposition / Velocity it will stop..
its a very common way to use kinematic rb to make a Break out Paddle
or Pong paddle so it collides with edges/borders
(unless this is another surprise 2D/3D difference)
these only referes to OnCollision events not collisions themselevs btw
indeed
The physics system doesn't try to send collision events for literally every pair of colliders in the world
(that would be painful)
so basically physics is if you want friction and "physics bouncing from hitting something or it hitting you"
So a 2d platformer or game that just does basic shooting should be kinematic rb?
yea kinematic controller is useful in 2D because it doesnt have character controller
so its the same thing just about
How to set it up. Explanations and demonstrations.
Getting Started with Unity
Support this Channel: https://www.patreon.com/SmartPenguins
Discord: https://discord.gg/FPPJf5r
Facebook: https://www.facebook.com/SmartPenguinsIO
Twitter: https://twitter.com/SmartPenguinsIO
Instagram: https://www.instagram.com/smartpenguins
Music:
"acoustic inspi...
that kinematic yellow block is going straight through everything, because it is being told to do so
theyre not even showing which method of movement they're using π€·
how do you even move a 3D kinematic rigidbody if not by MovePosition?
moving the transform is just doing it wrong
maybe they're using Translate π€·
i can just go check lol
Ima go eat lunch...but let me know when you see from testing pls π
Itll just go through the walls, move position is basically the same as updating its transform except its given velocity and can knock around other rbs in the time
guaranteed , at least with .velocity the kinematic rb will be stopped by walls
idk about MovePosition tbh as i dont use it
i just use .velocity
and it stops at colliders π€·
so kinematic would have to program their own colliders basically
to not move through walls
if you use .velocity guaranteed it wont
a 3D rigidbody does not move based on its velocity
which physics system are you talking about?
pretty sure I did it in 3D and 2D , one sec let me double check
Depending on what you're trying to move, a raycast should just be fine
idk. I know 2D. I know if I say βMovePosition to point Aβ, that goomba is getting to point A
also, yes, a kinematic Rigidbody goes right through a wall when using MovePosiiton
It will push any non-kinematic rigidbodies that get in its way
correct
kinematic rigidbodies are not like character controllers
The weight doesnt affect how much its pushed right? I remember this being a major issue in my game
no, because kinematic rigidbodies don't have a velocity
in 3D
they simply shove whatever they hit out of the way
correct
well, they certainly don't have a momentum, then :p
If you use MovePosition to move a non-kinematic rigidbody, then it will behave as expected when banging into a very heavy object
the heavy object barely moves
sounds like a lot of pain to save a bit of performance over just using non-kinematic π
so it goes through other kinematic objects?
we donβt normally pick RB types based on performance. we pick them based on what we need done
and pushes any physics?
A kinematic rigidbody is not affected by physics. It can affect other physical objects.
idk, sounds like a huge pain in the butt to do anything with them
collisions, program them yourself
gravity, program them yourself
the point is that they do exactly what you tell them, and nothing else
this is very useful for getting predictable gameplay
If I were making 3D bomberman, I would NOT use physics to make the bombs move
what if the bomb clips a collider and goes flying?
thats fair
I guess maybe its nice for puzzle games or things like that
if I want a lift that falls down with gravity, and ignores everything else (ignores friction, any sort of pushing, etc), kinematic RBs are what you want
or a platform that goes in a very specific way, every time, and ignores anything else as it goes on its movement
Like gravity or a wall collider
fair, I was thinking more just player/enemy-movement type stuff
sometimes we have really involved kinetic RB systems with character controllers. The reason to do that is to have 100% total control over every aspect of exactly how the player moves
hmm turns out I had the Kinematic stop with Rb.Cast 
because again: It only does what you tell it
performance-wise how much better is kinematic vs physics
cause outside of a few edge cases
I think thats all I care about atm
I feel like you're overthinking it
cheaper. because it does not care about anything in its way. But if you then supplement that with a bunch of raycasts and shit just to check collisions (to make it feel more like a dynamic RB), then there isnβt much saving
because you are doing what the dynamic RB was doing, but programming it yourself
Its more I have enough info that Im not going to bother since I like using physics objects unless its a lot better performance-wise
cause everything I have rn works fine
On top of what others have said, it's actually easier to get one to move how you want it because you tell it where to go. For example, making a homing missile is a lot harder using forces only compared to just moving it closer to the enemy
thats fair, Im working on that next actually lol
i made a homing missile in gmod when i was 12
Just pop open a new scene and experiment
again; we do not pick dynamic vs kinematic for performance. If you need something to bounce off walls, that calculation needs to happen. Whether you leave it to unityβs physics engine (dynamic) or code it yourself (kinematic), the computer is still doing that calculation if you want that object to bounce off that wall
figure I can just change the rb.velocity though and achieve basically the same thing tho
I hear what you are saying
the missile violently spun straight towards its target. brilliant machine.
but at this point unless its for performance Its not worth me changing stuff around to "fix it"
because kinematic rigidbodies ignore forces
kinematic rigidbodies only move how you tell them to, and ignore anything stopping them from doing what you ask
I guess if it ain't broke, right?
pretty much
I've messed with physics objects a lot and never had issues
so unless there was a performance reason to stop Im just not going to π
if I want a ball that goes in a straight line, or in a circle, or in a parabola etc, and I want it to be unaffected by everything, that should be kinematic
It never hurts to experiment and learn.
or have physics and a trigger collider?
it is way easier to program simple movement than to try to fight the physics system as it tries to push your object off course
cool
if I want a line, I want a line. I do not want a janky line that I need to correct to every time something gets in my way
appreciate everyones insights, I definately understand it all a lot better now π
(its like 1pm and I haven't eaten today so Ima go grab food lol)
back to my optimization question from yesterday, I do not understand why this code isn't super fast
the inner loop is normally called about 4 times, so it isnβt a massive iteration
why do you believe it isn't fast?
in deep profiler, this function just winds up costing several ms even for just a few dozen calls
and Iβm baffled
so range.x and range.y are usually both 2?
i only took out the deep profiler because my game was lagging
usually both 1 or 2
and in future, could be bigger, like 3-4
can anyone help me with my shop system ?
well first i added a coin system script called PlayerManager.numberOfCoins
can anyone create for me a shop system plz that has the character index and more things
no, we aren't going to write code for you.
I would strongly suggest reading #πβcode-of-conduct and #854851968446365696 before continuing
somewhat odd definition of 'little', creating a complete customized shop system, me thinks
no it dosent need inventery it just a public void ChangeCharacter(int index) and the deselected index need to be unactive
a shop without inventory, odder and odder, what are you selling? Software or Dreams?
oh fine wanna to see a video ?
no
not really
Please don't be toxic
i want to explain please i want to publish my game in playstore
This discord is not for us to code things for you. It is to seek help
but i like it βΊοΈ
i am like gentle man ill never break rules (only do not spam idk how i can stop it)
let me take a look on the rules
That's the first thing you should've looked at
Can we see the profile of the function ? Because if range.x and range.y are low, I hardly see what can cause performance issue.
it's all in self
all the sub function calls are like Vector2.ctor etc. It's almost entirely self cost
Does anybody know how I can make the trigger vibration motors on the Xbox Series X controller work in a script? There are no tutorials that I can find and the documentation about it is not helpful
If I have a box like this thats "rotated" How can I determine if the X here is "above" the Y so that I need to rotate "upward" to rotate towards it
Btw I am using the new input system
(for new input system): https://docs.unity3d.com/Packages/com.unity.inputsystem@1.7/manual/Gamepad.html?q=rumble#rumble
Is this how I should be doing it?
// Calculate the vector from the cube's position to the point you're checking
Vector3 toPoint = pointToCheck.position - cubeTransform.position;
// Calculate the dot product between the cube's local up vector and the toPoint vector
float dotProduct = Vector3.Dot(toPoint.normalized, cubeTransform.up);
// Check if the point is above the cube's local Y direction
if (dotProduct > 0)
{
Debug.Log("Point is above the cube's local Y direction.");
}
else if (dotProduct < 0)
{
Debug.Log("Point is below the cube's local Y direction.");
}
else
{
Debug.Log("Point is on the same plane as the cube's local Y direction.");
}```
seems way harder than I feel it should be
Vector3 localPos = myBox.transform.InverseTransformPoint(positionOfTheRedX);
if (localPos.y > 0) {
// it's "above"
}```
That doesnβt tell me how to use the trigger rumble on Xbox Controllers
awesome thanks!
Gonna be honest IDK what that is or how it's different from what I'm talking about
here is my game
is that like a new thing where only the trigger "vibrates"?
it needs a shop system right ?
Supposedly itβs been a thing in Unity for a while, but the documentation is useless for the impulse triggers (trigger vibration)
is this how I would determine the angle to rotate to face that RedX or if there another nice unity function for that
Vector3 localPos = myBox.transform.InverseTransformPoint(positionOfTheRedX);
float angle = Mathf.Atan2(localPos.y, localPos.x) * Mathf.Rad2Deg;
which face do you want to rotate towards it?
your local up?
your local right?
Vector3 dirToX = positionOfTheRedX - myBox.transform.position;
Quaternion rotationToApply = Quaternion.FromToRotation(myBox.transform.right, dirToX);
Quaternion targetRotation = myBox.transform.rotation * rotationToApply;```
now you have a quaternion that represents the required rotation
sweet thanks
You can use this with Quaternion.RotateTowards or Quaternion.Slerp or whatever to make it smooth
or rather:
Quaternion targetRotation = myBox.transform.rotation * rotation;```
gotcha...Im wanting to "cap" the rotation so it only rotates a certain amount/second
yeah Quaternion.RotateTowards is good for that
so I would just use it like this right? ```cs
Vector3 dirToX = positionOfTheRedX - myBox.transform.position;
Quaternion.RotateTowards(myBox.transform.right, dirToX, rotateSpeed);
No you'd use this code ^
and then:
myBox.transform.rotation = Quaternion.RotateTowards(myBox.transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);```
awesome thanks...was trying to work in out since my last message and was about 80% of the way there
public Dictionary<Bullet, ObjectPool<Bullet>> bulletPools = new();
can I do a Dictionary like this?
not sure if it will see different "Bullet" prefabs as the same thing
I would use something like a BulletType enum as the key
I was doing that
I think what you have would use INSTANCES of bullets as the key
but I wanted to create prefabs with different bullet speeds
but yeah I think you are right, I should just set bulletspeed in code π
(for anyone wondering...yes you can do it the way I had above ^^ )
You could also do strings as keys, take the enum and concat it with another enum to make a string.
Like FireBullet_Fast, FireBullet_Homing
Or something. I dunno
Edit: or maybe a tuple instead. Not sure which is less dumb haha
Ah interesting, good to know
the prefab as a key is fine imo but the only downside is its kinda annoying for the object itself to return itself to the pool. If you try to store the prefab reference on itself, itll update to the instance of the object when instantiated
I dont fully understand the second part but I do have it do this
pool.Release(this);
however other classes are the ones that call the pool to create it
if you have an object try to reference its own prefab, itll instead reference the instantiated object when spawned
but thats really all
ah gotcha
if this is intended as a map of prefab -> object pool for that prefab, yes you can definitely do this
you just have to be very aware of which Bullet reference you're dealing with at any given time. Accurate variable names helps with this.
Vector3 targetpos = target.center.position;
Vector3 dirToX = targetpos - transform.position;
Quaternion rotation = Quaternion.FromToRotation(transform.right, dirToX);
Quaternion targetRotation = transform.rotation * rotation;
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * 450f);```
This code from earlier looks right right?
my bullet isn't ~~rotating ~~ moving towards enemy
(debug shows this code is executing)
nvm Im dumb sorry
never re-set the velocity π
Having some issues with git. Specifically, .unitypackage files. I'm trying to work on a friend's project, but we're having a lot of issues with metafiles randomly being added and removed from the repo.
Currently, they have a slurry of unitypackage.meta files that unity says need to be pushed to the repo. The problem with that - our .gitignore, and every template I've looked at, excludes any *.unitypackage files, but not *.unitypackage.meta files.
Is this intentional or not? I can't see why you'd want the meta files, but not the actual package files.
why do you have .unitypackage files in your project?
Not my project so I can't speak to how it's set up, but here's a sample of the git status:
I did suspect that maybe the .unitypackage files aren't meant to have .meta files alongside them, but when I asked if they had ever moved their packages, they said no.
I suspect that those assets are supplying additional context in a .unitypackage file which is then unpacked into the assets folder and deleted leaving the orphan .meta file behind. you can simply add a .unitypakage.meta to your gitignore
I considered that too, but the .unitypackage files are actually on this person's pc, they aren't orphaned .meta files.
I would ignore them both in that case
If I have an object about to touch an area effector (or something that gives force), and it enters this region in between frames, (in between fixed update frames), does force get applied during those frames before the fixed update frame?
like:
Update - not in effector
Update - yes in effector
FixedUpdate - Yes in effector
would the object be getting pushed between the 2nd update and fixed update?
Im not sure but my take would be that the update will see that it is indeed in the effector but not apply force
And the force would be applied
Next fixed update?
"Resolution.refreshRate is obsolute: use refreshRateRatio instead"
Application.targetFrameRate = Screen.currentResolution.refreshRate;
//Application.targetFrameRate = Screen.currentResolution.refreshRateRatio;
cannon convert type UnityEngine.RefreshRate to int
when I try the top it says obsolute, when I try bottom it throws error π
access the refreshRateRatio's value property
and next time perhaps take a look at the docs
does anyone have any idea why float forceMagnitude = Mathf.Sqrt(2.0f * Physics2D.gravity.y * _bounce); returns NaN?
_bounce is 4 here and gravity is set to -47, so nothing weird going on here. i tried setting physics to -9.81, but same problem
*gravity, not physics
the square root of a negative number is NaN
I tried that...when the docs dont have actual code I get pretty lost
thanks!
ah, I just have to grab that value and then change it into an int
thanks π
leave it to Unity to make something that works nicely have to have a cast now
very fun
hey guys, I need to make a single sctipt for all weapens and make the children inherit it, but when I use OnTriggerEnter, and I get triggerd with the child object it doesn't detect, the funcion is public and the children has a collider that is triggerd.
Use the collision matrix and validate the collision in the method
Are you saying the child objects inherit a script that is in the parent?
May get a little messy
I have a weapons script that have many children like postol,smg.., the children are objects but the parent is just a script
Oh ok. Then yeah, just use a collision matrix and validate the collision. What specifically is the issue?
it deesn't detect
huh? that's confusing. each weapon should have their own instance of the script. if their just child GameObjects of any empty GameObject with the script, that's not inheritance . . .
Go through this:
https://unity.huh.how/physics-messages
Yeah, I'm getting a bit confused too. Like are we talking hierarchy?
I THINK they mean, only the derived classes are on objects anywhere, the base class isn't on any object
this might clear things
Weapons Script:
public class Weapons : MonoBehaviour
{
public void OnTriggerEnter(Collider other)
{
print("test");
}
}
Pistol Script:
public class Pistol : Weapons
{
}
Yeah, the issue isn't really to do with inheritance, but physics messages. Did you go through that link at all? There could be a number of causes. The biggest one that gets people is that for OnTriggerEnter, you need a non-kinematic rigidbody on one of the objects
I'm going throw it now, and try to solve it thx
ok im changing the layer of a prefab halfway through the game to ground however when the game ends the prefab doesnt go back to its original layer in the editor
why is that
hello, I am currently trying to activate the children of my parent object through a script in the parent object. I figured out how to reference a variable from an entirely different script but now I am struggling with figuring out how to activate each of the children based on the value of the variable from the other script. How do I go about this?
Are you actually changing the prefab file?
Or you mean a gameobject that was instantiated FROM a prefab?
Where is the value that you want to base it on? I don't think you can get values from disabled gameobjects
The value is from an entirely different object and script