#archived-code-general
1 messages · Page 17 of 1
Lerp interpolates between a value of 0 to 1. As 0 increases towards 1, the same reasoning happens to point a. It will increase towards point b.
GetComponent<Rigidbody2D>().position.y;
this is to get position of current object that has script. how do i get position of a different game object?
oh iknow
maybe
get a reference to the object you want to get the position from. how to get a reference: https://www.youtube.com/watch?v=Ba7ybBDhrY4
also don't crosspost
not really sure where this question might go, but i'm having this issue where unity forcibly takes application focus after domain reloading (e.g. after making a script change in visual studio). i think this started happening after i upgraded to 2022.2. anyone know how to disable this behavior?
audio.Play();
does this not work with prefabs?
i read something about the prefab instance getting destroyed before it can play the sound but even without destroying it it's not working for some reason
audio is an AudioSource
Hey is it in any way possible to have an infinite tilemap for a sidescroller? Using ruletiles and adding pre-made segments or rooms to the right side but always connecting those rooms using the ruletiles rules? I cant find anything about this on google?
If yes, how would I do it? Make the pre-made segments their own tilemaps as prefabs? Another way? How do I spawn them in so the ruletiles connect to the other segments?
Any help is much appreciated!
okay wow so i figured it out - if you have multiple unity projects open, any domain reload will force the project whose domain is being reloaded to take application focus, even if your previously focused application isn't unity.
Hey
I have error SerializationException: Type 'UnityEngine.ScriptableObject' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable., while my ScriptableObject is serializable (I guess)
you don't want/need [Serializable] on a ScriptableObject derived class ever
What are you trying to do when you see that error?
Well, I created SaveSystem and I get this error when I want to save player inventory
return (Dictionary<string, object>)formatter.Deserialize(stream);
I guess it is this line
But i am not sure
You should never use BinaryFormatter
period
and Dictionary<string, object> is just an insane thing to use too.
If be honest
I did it from tutorial cause I have not idea how it could be done
So I used to use trailer and change it on my way
find a different tutorial
Thx. I'll post there.
Is there a way to set a variable that can be accessed by any class without the need of instantiating, like a static method? For example, setting a material to that variable that any class can simple call MaterialScript.material to get
Static variables
but they're often not a good idea, you're fully responsible for their lifecycle
I tried them, but they didn't work how I expected, i.e., you still have to set the variable in runtime. I was more looking to something that could be set in the inspector, like you do on classes that are on objects, but on a script itself, but that doesn't seem to exist by my trial and error.
ScriptableObject can serve this purpose
Or just use a singleton
hey how would I set an integer to a gameobjects place in the array?
I'll research both, thank you for the tip
So, each object in this array has an integer called "placeInArray"
I want to set that integer to its place in the array of a separate manager object
for (int i = 0; i < myArray.Length; i++) {
myArray[i].placeInArray = i;
}```
and this is an update function?
heavens no
More like Awake of the manager
Okay so the problem is that objects get added to the array over time...
You should be using a List then, not an array
and that's simple:
public void AddAnObject(MyScript objectToAdd) {
int listLength = myList.Count;
myList.Add(objectToAdd);
objectToAdd.placeInArray = listLength;
}```
I see, thank you
Can I ask why should not I use Binary Formatter?
Every next tutorial I am looking in uses it
I showed you why already. Look at different tutorials
and the "MyScript" here would be referring to the script attached to the individual objects?
So, each object in this array has an integer called "placeInArray"
It's whatever class that is
Got it, thank you
Doesn't seem to be what I'm looking for. I need a variable that can be set outside of runtime, like a static method that doesn't need its class to be attached to an object to function. Anything that I have to create in-scene will not work. I've settled on an static variable being set by the game controller on awake.
Hey Guys, I'm Currently developing a platformer with a shotgun as the main gimmick. Basically when the Player shoots the shotgun, the Player should fly backwards with wanted value.
My Problem is, that while getting the angel for the desired direction, the cursor changes the amount of the force depending where it's currently on the screen.
Since I want a constant value for the knockback, dose anyone know how I could change the Formula so that the cursor affects only the direction and not the force applied to the Rigidbody?
Code I'm currently using:
// This is all the needed Code moved Into the shoot Function (meaning some variables are declared elsewhere)
private void Shoot()
{
mousePos = cam.ScreenToWorldPoint(_context.ReadValue<Vector2>());
_force = new Vector2(mousePos.x - transform.position.x, mousePos.y - transform.position.y);
rb.AddForce(-_force * knockbackForce, ForceMode2D.Impulse);
}
If I should provide more Info or examples, ask :)
Normalize the force vector to be of unit length (removes magnitude, keeps only direction) and then multiply that unit vector with your desired knockback force.
i.e.
_force = ...
_force.Normalize(); // makes it unit length
rb.AddForce(-_force * knockbackForce, ForceMode2D.Impulse);
Gimme a sec, going to test that real quick
At that point, _force needs renaming to something like forceDirection or the like, to reflect its intent
It works! Thank you :)
ScriptableObjects are not in scene
They are assets
how would you make a climbing system with animation rigging package in unity, more specifically with IKs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class Hover : MonoBehaviour
{
public LayerMask layerMask;
public Camera mainCam;
public bool IsHovered = false;
public GameObject selectedobject;
void Update()
{
int NoOutline = LayerMask.NameToLayer("NoOutline");
Ray ray = mainCam.ViewportPointToRay(Vector3.one/2f);
if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, layerMask))
{
if (hit.transform.tag == "Hoverable")
{
hit.transform.gameObject.layer = LayerMask.NameToLayer("Outlined");
Debug.Log("Changed layer to layer1");
selectedobject = hit.transform.gameObject;
IsHovered = true;
}
else
{
IsHovered = false;
}
if (IsHovered == false)
{
if(IsHovered == false && selectedobject != null)
selectedobject.layer = NoOutline;
selectedobject = null;
}
}
}
}
i made this script so that when i hover objects with the tag hoverable , it will change the layer of the object , change the bool value ,and when im not hovering anymore , it will change the bool value and the selectedobject will change it's layer before making the selected object null
bug : when i hover on obj1 then obj2 , with both of them having the tag , the first hovered gameobject dont swap layers too
how can i detect this object change so i fix this bug ?
Oh, from what I saw you had to use it into a scene for it to function, tomorrow I'll check it out again
they literally cannot exist in a scene
they are assets
you have to reference them to access their data of course
Sorry, that's what I was trying to say, but I'll check them out nontheless
Hey, asking it here again because #💻┃code-beginner is busy, I used the Brackeys guide to set up movement using a 3rd person camera, and I wonder how I can make it, so the direction which the character is facing is always relative to the camera, and not the movement?
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
if(direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; //Determine which way the character should face
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); //Take the targetAngle and smoothen the turning a bit
transform.rotation = Quaternion.Euler(0f, angle, 0f); //Set the rotation to the angle
Vector3 moveDirection = Quaternion.Euler(0f, angle, 0f) * Vector3.forward; //Make it so the way forward is relative to the camera
controller.Move(moveDirection * speed * Time.deltaTime); //Move the character
}
}```
transform.forward will give you a direction the player is facing
yeah, I want that to be relative to the camera essentially
well now you want conflicting results
It's a little hard to explain
you know how a lot of 3rd person games have 2 camera types
actually
over the shoulder sounds like it
kinda like aiming
A good example is GTA5
So you want the rotation to be independent?
while moving normally you can go in any direction
it's called third person with strafing
but while holding down on the sight, you can strafe left and right
thanks!
yeah that's basically what I want to achieve
how can I do that?
The camera has to be positioned around the player. Start there with some algorithms related to circles
hint, Cosine Sine
I used Cinemachine for that
Hey
I want to know how to do a jump that increases in height the longer you have the jump button held down.
Sorry, I'm not familiar with Cinemachine
Like the Mario jump
oh
I think blackthornprod made a perfect guide on that
send me the link if you can find it.
Imagine jumping like a jetpack
the longer you hold it down, the more your height off the ground increases
In this unity tutorial we will take a look at how to make a cool 2D platformer controller !
The character will be able to jump higher the longer you hold down the jump key, move left and right and flip to face the direction in which he is moving !
-------------------------------------------------------------------------------------------------...
is it possible for one internet tab with Unity to read what's going on in another tab with Unity?
at that point it's really a javascript/web development question
something like https://dev.to/dcodeyt/send-data-between-tabs-with-javascript-2oa for example
I'm trying to add sound to this flappy bird clone I made with GMTK's tutorial.I don't understand how to get the sound to work though.
what isn't working about this?
It keeps saying "ArgumentNullException: Value cannot be null".I gave the bird game object an audio source component and I included the right mp3 to use for the audio clip.
sounds like the audio clip isn't assigned to the audio source
Are you sure?
this screenshot doesn't mean much
show what sfx_wing is assigned to in your script instance
Debug.Assert(sfx_wing.clip != null, "The clip is null", sfx_wing.gameObject);
throw this one line above the .Play() call and it will yell at you when the clip isn't null and you can even click the error to highlight the gameObject where it is null
Okay,so I see now that the reference needs to be assigned.So how do i assign the clip to the reference?
you don't
you assign the audio source
So how do i assign the audio source?
drag the audio source that has the clip assigned into the slot in the inspector for this script
so just to confirm, it was actually the sfx_wing variable that was null and not the AudioClip assigned to the AudioSource?
it was the variable
yeah i really dislike that the Play method can be called on a null object and not throw an NRE but instead throws an ArgumentNullException
How could I get the button that is clicked through a addlistener? The button is in a list and I have a for statement putting the addlistener on each button
foreach (var button in myList) {
var theButton = button;
button.AddListener(() => SomeFunction(theButton));
}```
or whatever other parameter you want to add
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
public void EnableKinematic()
{
rb.isKinematic = true;
}```
I am trying to access the rigidbody of not the gameobject that I have the script attached to but the object that I have attached the script manager to. This is turning off the isKinematic for the script manager
Any ideas? Let me know if more context is needed.
GameObject.FindObjectOfType<scriptmanager>().gameObject
GetComponent<Rigidbody>(); this gets the RB of the GameObject your script is attached to
the simplest way to get some other one is just to drag and drop it in the inspector instead of assigning it in your code.
Yeah, I thought about that but the issue is there is an .fbx with about 60 different parts so I would have to go and do that for each. I was wanting to find a way that would scale. But if that is the best way then I can do it
Would this not be getting the script managers gameobject?
Thats what you said right?
what exactly are you trying to do?
I don't understand
is this for a ragdoll?
No, sorry. I did a poor job explaining. I have the script attached to the script manager (GameObject1) and then am needing to access a function in the "On Release Hand" of a seperate game object (GameObject2). I am needing to turn off the kinematics for the GameObject2 but since the script is attached to Gameobject1 then it is turning the kinematics off for the script manager (gameobject1)
ok so what was all that about "60 different parts"
you're only mentioning two objects here
I am needing to do that for all 60 parts
for this you just directly reference it:
public MyOtherScript theInstance;
void DoSomething() {
theInstance.SomeFunctionOnMyOtherScript();
}```
You can use GetComponentsInChildren<Whatever>
and loop over them all
using UnityEngine;
public class FollowCursor: MonoBehaviour
{
void Update()
{
// Get the mouse position in screen space
Vector3 mousePosition = Input.mousePosition;
// Convert the mouse position to world space
Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
// Get the direction from the player to the mouse
Vector2 direction = (worldMousePosition - transform.position).normalized;
// Get the angle of the direction in degrees
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
// Rotate the player to face the mouse
transform.rotation = Quaternion.Euler(0, 0, angle);
}
}
``` When I start the game the player's rotation is set to the left, is there a way to make it start towards the cursor so the player rotation is not offset?
Preferably I would like to just mention the specific game object that I am holding. Although I do think that would be a solution that would work
now I'm back to not understanding
are you going to be "holding" one of the 60 parts?
yes, there are esesntially 60 gameobject2's
Just have a Rigidbody currentlyHolding; reference
have it always refer to whatever you're currently holding
and just do what you need through that variable.
okay, I will give that a try. Thanks everyone.
I'm writing (rewriting) a mod for a Unity game. I created a Basic UI that has a few buttons/text inputs that sit under a Canvas within the editor. I moved the Canvas into assets and created an asset bundle for the Canvas. Within the mod when I load/Instantiate the canvas I see it, and all of the elements under it. However I can not interact with anything. Attempting to find child components returns null. How would I get access to the inner buttons/inputs (During runtime only because I am not actually doing any building in Unity Editor, just using it to create the asset bundle)
Or am I better off sticking with IMGUI
Im trying to restructure my character controller, the way it works now is I have a parent with a bunch of scripts that reference various parts of nested child objects (specifically the rigidbody, collider, various skinned meshes and specific bones from a rig hierarchy), the problem is I have different characters that have different rigs/skinned meshes, what might be a good way to have the parent (or some other system maybe?) link the references from x character prefabs? Atm im thinking I could give the parent a ScriptableObject and setup the references on each character there (then pass the SO to the parent when im spawning x character), but I feel as characters become more complex, that approach may get more unorganized, is there another way I could approach this problem, or does this sound normal?
However I can not interact with anything
Missing EventSystem or GraphicRaycaster perhaps?
Attempting to find child components returns null
Show what you attempted?
so im trying to make an interaction event on the inspector tht i can add it looks like its trying to work but it doesnt pop up
looks like the selection is filtering to Texture2Ds, but then you're checking if they're sprites?
Is 2D Unity Navmesh strong?
Or is it recommended to wright my own pathfinding algorithm ?
oh, which one is the correct one ?
I'd go the SO route first, simple to implement. Any change to references happen on that one asset tied to the prefab . . .
you tell me?
I have no idea what you're doing
Looks like Sprite maybe?
Well I don't know in unity waht I have selected says texture type sprite 2d and ui
but idk what the difference between texture and sprite is
suffice it to say they're different for now
so you can't say "give me a bunch of Texture2D" and then say "if any of these things are not SPrites, throw an error"
of course an error will be thrown
why not just filter to Sprite?
because in line 16 it takes in textures and thats someone elses code to manually set pivots for each sprite in a spritesheet
and for sommmmeee reason it takes in texture
which i dont understand
I was under the impression I can't use the Editor's event system because I cannot include the script inside the asset bundle.
I would ask the person who wrote the code
if you don't have EventSystem in the scene, naturally UI will not work
not sure what you mean by "Editor's event system"
I'm not building a game - I'm adding a mod to the game
I know that
Is there a way to invoke an event in my coroutine if the coroutine was stopped?
Fair enough, just wondering if there was a more elegant approach, but your right it would only be one point of change, so ill stick with this until it causes problems - thanks for the response
coroutines that were stopped are not running. They can't do anything
I'd like to know if my coroutine was stopped tho👀
I'm assuming you're doing VRChat
https://docs.vrchat.com/docs/whitelisted-world-components
EventSystem is specifically whitelisted
would you say in order to edit a spritesheet that would require accessing a texture or a sprite though
because maybe i can just change it
fire an event when you stop the coroutine
Is your coroutine public? What can be allowed to stop/access it directly? Or is it only stopped if the object is SetActive(false) or yourScript.enabled = false from some other script?
Character's death stops all coroutines on the character
Just fire the event in the Die() function
I am not - its a mod for PlateUp. You got the buttons works -> I moved my Canvas and an Event System into an empty GameObject and added that gameobject as the only asset in the bundle - now everything loads and is clickable. I suspect I'll now have to loop through that parent game object to assign the proper listeners
i don't know much about spritesheets
oh well I will try around im sure that i can find it out, not like there is many options :D
thank you for your assistance
Guys, I have an interesting conundrum here that I need a little help understanding
Debug.Log("Incoming damage is spell:" + incomingDamageTable.spell);
Debug.Log("Incoming damage is player:" + (incomingDamageTable.player != null));
if (incomingDamageTable.player != null && !incomingDamageTable.heal)
{
if (incomingDamageTable.spell)
{
if (damageTable.Count == 0)
damageTable.Add(incomingDamageTable);
Debug.Log(damageTable[0].spell);
}
}
So how can the initial 2 debugs return true
while the final debug return false
How do I remap .unitypackage files back to Unity? For some reason WinRAR captured that file extension, and when I open with (what appears to be) the unity exe, it tries to open unity hub.
When by all means the final debug should echo the first debug since it should just be a duplicate of the first
that's not a code question let alone a unity question. search "clear default app" for your operating system
I mean, it's a unity question, that's sort of nitpicky.. but.. the point is that the default app is currently unity.exe, but unity hub is opening, not unity.exe
Does adding an entry to a list change its values somehow?
In this case it must be though as there is no other way for this behaviour to occur?
Are you familiar with "by reference" and "by value"? putting elements into a list won't copy it - so if you're changing the elements elsewhere, they'll be changed inside your list
Post the code, though, the problem might not be what you think
I already posted the code directly above
your indentation is making this hard to understand - you do see that, yeah? that the Debug.Log under the if statement isn't inside the if clause?
first i would clean up that code
(also just FYI you generally should embed your values in strings using the interpolation operator $, it'll make it a lot easier to read)
you are also missing a brace, so the final debug will not be conditional on the if (damageTable.Count == 0) statement
Debug.Log($"Incoming damage from spell is {incomingDamageTable.spell}");
Its not supposed to be conditional on the if statement
would have tricked me with the indentation that was showing a different intent then what the code was doing
You haven't really posted enough code to understand the problem, though - you asked how the first two lines could both print true but you didn't show us how you're assigning those values...
so is the 3rd debug printing?
Yes
but it is the exact same value as the initial debug
just after being added to the list
that would be expected with the code you show
you are printing the incoming spell, then adding it to a list then printing the first element of the lists spell which is the same element
Debug.Log($"Spell: {incomingDamageTable.spell)}";
Debug.Log($"Player: {incomingDamageTable.player != null}");
if (incomingDamageTable.player != null
&& !incomingDamageTable.heal // heal? or spell?
&& incomingDamageTable.spell
&& damageTable.Count == 0) damageTable.Add(incomingDamageTable);
is that what you mean?
and then after that you would type Debug.Log(damagetable[0].spell) and it would be false despite the initial debug being true
It doesnt retain its value and I don't get why
I mean, you're adding something to a list but you're assuming that damageTable[0] is the item? if there's anything else in the list, you're looking at the wrong item. Items are added to the end of lists, not the beginning
There is nothing else in the list if not damageTable.Count would not be equal to zero
well you still print it no matter the length
but you aren't debug.logging if count = 0
you just only add if 0
Yes but I can check in the inspector and see that there is nothing in the list
you're debug.logging it all the time because your indentation is wrong
would strip it down to the most simple case and test your assumptions
you don't really understand.. lemme rewrite your code
Debug.Log("Incoming damage is spell:" + incomingDamageTable.spell);
Debug.Log("Incoming damage is player:" + (incomingDamageTable.player != null));
if (incomingDamageTable.player != null && !incomingDamageTable.heal)
{
if (incomingDamageTable.spell)
{
if (damageTable.Count == 0)
{
damageTable.Add(incomingDamageTable);
}
Debug.Log(damageTable[0].spell); // this is printed even if the damagetable.count is 0.. in fact, it's always printed! because you add to the table BEFORE printing this anyway, and might not even refer to the thing you just added
}
}
i haven't changed your code aside from fixing your indentation and adding brackets to highlight that what your code is doing - the code as i wrote it is identical to yours, but it should be obvious now why the debug.log in the block isn't doing what you expect it to be doing
It will always refer to the thing I added because I am testing this once
Also just FWIW your variable names make it really hard to decipher your intent. Booleans should have "is" or "did" or "does" or "can" before them so they just read like english. Like.. isTargetAPlayer or isHealingSpell
Not sure if this is even possible or not, is there a way for me to take this code:
public AudioClip GetClipByName(string clipName)
{
foreach(var clip in _clips)
{
if(clip.name == clipName)
{
return clip.clip;
}
}
return null;
}
And not only return a clipName but also force it to play through a specific audio source?
(otherwise you ought to paste enough code so we can see what .spell and .player and .heal and damageTable actually are
Yes - is the audio source linked in that monobehaviour?
It's not at the moment, I'm just now getting started. This is a tool I'm making
I can put it there however
public void PlayClip(AudioClipType type)
{
AudioClip c = AudioDatabase.GetClip(type);
if (c == null)
{
w($"No audio clip found for {type}.");
return;
}
_sfxSource.PlayOneShot(c);
}
something like this
and GetClip is:
just maps enums to audio clips, but you have the right idea
just get the clip, and pass it to PlayOneShot()
looping over your clips each and every time looking for a string comparison is probably going to be a bad idea, but you'll find that out later 🙂
Well the reason why is because I'm doing this in the tool:
Sure, that's fine
and the audio manager is in your scene? make sure it's got an audio source and you're good
Yeah it's in the scene.
I would like to not have to hardcode the audio source either, but I'm assuming looking for the clip and the source will eventually get to be a lot?
clean up your code, too, maybe:
public void PlayClip(string clipName)
{
AudioClip clip = _clips.Find(x => clipName);
if (clip == null) return;
_audioSource.PlayOneShot(clip);
}
What do you mean by hardcode the source?
Just declare it and link it in the inspector
Or if you're making audiomanagers elsewhere in your game and don't want to forget that step, in your OnEnable() make a GetComponentInChildren<AudioSource>() and have it throw an error if it can't find one
(the name audiomanager to me, though, implied a singleton, so you'd only need to do that once, ever, then forget about it)
Yeah I think I'm overthinking what I'm trying to do lol
Yes it will be there always
I'd personally use scriptable objects for something like this, but if that's foreign to you, don't worry about it too much, it's not really required
Then yeah, you're golden.. if you want I'll even show you the entire source code for my audio singleton
does music, sfx, etc, but isn't too complex
the only thing AudioDatabase is doing (in mine) that you'd need to do on your own is finding the clip you want to play based on a string
(mine uses enums but that's nbd - you can use strings)
It's not foreign, it's kinda hard to explain what I'm doing really. I just didn't want have the player create a scriptable object for every audio clip or am I overthinking it?
players don't create scriptable objects.. you do
Well
Think of a scriptable object as a uh.. data file
OK, so.. they don't create an SO for every audio file, they create one for "all" of them, typically
mine look like this:
the SO is sort of .. where you link the files to the enums - then anywhere in the app, you just ask the SO for the clip you want
That way you don't have to .. link the clips you need to every audio source through your entire app
But if you're using an AudioManager singleton that you plan to have everywhere in your app, and you don't have any need to have multiple listeners or audio sources, then you're fine
Yeah. I do want multiple sources though, for the different settings.
well at the call site what do you want it to look like. you provide a source and clip, or just a clip and it knows the source based on it?
I found the problem and it was unrelated to the code I pasted since it was a bastardized version of the actual code which would probably give you brain damage. Thanks for the advice and putting up with my stupidity anyhow
You probably don't want multiple sources but rather multiple listeners? What do you mean, different settings?
There should only be one listener (acutally I think there can only be one listener?) - if you have settings like volume/position/etc, you change those values on that listener.
no he means mulitple sources, with differnet settings each
No I want multiple sources
SFX, UI, Game, Master, etc
OK, that's fine.. what do you mean with different settings then?
really would just have multiple lists of clips, one for each source
ok, so, no problem... i'd still route all of those through your audiomanager from what I understand
so when you play a clip it figures out which list its from and plays with the associated source
Hmm.. maybe, but maybe not depending on if master should intercept that
yeah I'm trying to figure it out now. I think I have to link it through the PropertyDrawer or it won't properly pick it up
Since I'm using a custom GUI
I'd probably but the master settings on the listener but then have all of the sources play at different volumes
That's how I have it
Master is at the top then all others derive from it, but can be changed individually
Is it possible to create a shortcut in unity at runtime? Say, invoking a function when certain keys are pressed and held in a specific order
If the order is important, you could probably store your keypresses in an array or stack - otherwise if you just want to know if certain keys are currently held down, you could check for them in Update, if your using the "new" input system, you could subscribe events to an action map, or check the "wasPressedThisFrame" or "IsPressed" of the "current" Keyboard, assuming this is only important for the keyboard
Great, thanks
this is fine. you can create a source for each type of sound and route them through a corresponding mixer which all ties into the master mixer . . .
Do Joints work for you? Something like https://docs.unity3d.com/ScriptReference/FixedJoint.html ?
yeah I didnt realize spring joints were a thing. Seems like its working, thanks!
Will transform.GetComponentInChildren<T> return all of the type in all of the children or only in the first child it encounters them?
Insert an 's'.
So I have a Object(A) that is moving diagonally, I have 2 child object(B & C) on A.
A is being tweened to move diagonally.
B & C are getting a RigidBody2D added to them so that they can move away from each other with physics by adding an inpulse force to them.
B gets a force at Vector2(1,1)
B gets a force at Vector2(1,-1)
However, they are not moving in different directions at all. They stay as one.
How does rigidbody2d work when it is on a child? and the parent is constantly moving through tweening?
🤦
Why would you need a custom inspector for that?
#💻┃code-beginner message Anyone got ideas
Im trying to access ParticleSystem.VelocityOverTime and the parameters for orbital and offset are available but linear doesn't appear to be. Is there another way to change it or is it not accessable from script?
In the inspector?
#↕️┃editor-extensions
Cant you do something like if(Attacking) {bot.SetDestination(bot.transform);} //sets destination to itself so it stops moving. Else {Do the destination finding stuff here}
Lets try
To a certain extent you could do that, but it's a simplification of a larger pattern, the state machine. Your object is in patrol (or destination-finding, but I'll simplify it to just 'patrol') mode, until it is attacked or finds the enemy, at which point it switches out of the patrol mode into attack mode, until the enemy (or itself) is dead, at which point it probably switches back into patrol. You can special case this, and it'll work pretty straightforwardly, but if you have more states, or substates, the code gets very complicated very quickly.
In any case, if you're using Nav Agents, there are other simple ways to stop navigating, IIRC.
Yeah I guess u could set it's speed to 0 or i think use NavMeshAgent.isStopped to stop navigation
So I use A* Pathfinding, in general, and so it has an 'AIPath' object that gets associated with the object that moves, and I set 'canSearch' to false, and it stops looking for the next step to take. I...really should explore the basic nav mesh agents again, and see what they offer, but I vaguely recall a similar operation available on it. Essentially turning off nav mesh movement for a while.
That said, I also use Behavior Designer, which is killer for just this kind of thing.
Oh my god I forgot to respond sorry. But yes that does work
@frigid anvil @warm wren Thanks
Might try this to
That also works
I don’t know what I’m doing
I want to be able to use different methods from this state here, so I made an action that I can change for every state
That is not working
How do I do something like this
I can’t assign any methods to it. Or at least i don’t know how
How are you assigning the methods?
You mean from code or from the inspector?
I don’t know how. Since it doesn’t appear in the inspector but I don’t know how I’d do it through code
Which do you want to do
Inspector or code
Inspector preferably?
When I used unity event I couldn’t find the methods either
But it doesn't make sense if it's for runtime states though...🤔
Find what methods
They need to be public.
When I go to assign the methods in the inspector with a unity event, it’s just a bunch of random scripts, I can’t find anything from the state
Wdym random scripts
What are you looking at
You need to drag an object into the slot
Not a script
A ScriptableObject or GameObject
You need to reference the object which methods you want to reference.
So in your case it needs to be an instance of TextStates
(e.g. itself)
But this is a scriptable object, you can’t put that in the scene? It needs to be a monobehavior
Why are you talking about scenes
We're talking about the slot in the inspector here
Unity Object instances exist not only in the scenes. SO instances and components on prefab GOs are all instances too.
No
That's the script
Wrong thing
Drag in the very asset whose inspector you're looking at
Oh shit ☠️
Script asset is not an instance of the class that is written in it. It's just an instance of a text/script asset type(not sure what type exactly).
hey, for some reason my gameobject with rigid body and a collider wont collide with my other gameobject with collider, any idea why? (specifically it does detect oncollisonenter, but it wont lie down on the collider, it passes thorugh it instead)
sounds like you're moving the object in a way that doesn't respect collisions
im moving it with transform, position, should i move it with rigidbody.moveposition instead?
i had some problems with it
Moving with the Transform ignores physics
You need to move it via the Rigidbody, yes
MovePosition isn't really the way though no
you'd move it via setting velocity and/or adding forces
yea i heard it doest work well with other bodies types than kinematic
could you give an example of code?
moveposition should be used when the rigidbody is kinematic
rb.velocity = something;
ah alright, ill try that, thanks
bruh lmao
on the other hand though i might try it you have no idea how much issues is my powerup system generating
public static bool RayCastOnceNonAlloc(Vector3 origin, Vector3 direction, RaycastHit hit, float maxDistance, LayerMask layermask, QueryTriggerInteraction querry = QueryTriggerInteraction.UseGlobal)
{
RaycastHit[] temp = new RaycastHit[1]
{ hit };
int hitCount = Physics.RaycastNonAlloc(origin, direction, temp, maxDistance, layermask, querry);
return hitCount > 0;
}```
would you think this is better than the regular raycast method?
in terms of performance and garbage generation
Are you asking if this is better than RaycastNonAlloc?
No compared to regular raycast
the bool one
I think it would be the same speed
because the whole point of the NonAlloc method is to avoid having to generate garbage
but since you created a RaycastHit[] temp = new RaycastHit[1], it gets destroyed immediately after the function returns
You need to reuse your buffer to get benefit from it
perhaps I should use ref/out keywords for RaycastHit?
And your code won't have the same result as regular Raycast when there is more than one hit
yeah I'm trying to make it single hit just like the regular raycast
also, what?
No. That's not how RaycastNonAlloc works.
When a full buffer is returned it is not guaranteed that the results are the closest hits and the length of the buffer is returned.
Are you using ChatGPT?
no, I wrote the code myself, I told gpt to optimize it
and it told me to get rid of the optional parameter for performance
like what
I know RaycastNonAlloc returns an array of hits just like RaycastAll, I'm trying to replace the regular (bool)Physics.Raycast() method by using the nonalloc method
Physics.Raycast is already non alloc and their behaviour is not same as I quoted
quick question- what did i mess up? the bullet is chilling where it was spawned
{
bulletRB.velocity = Vector2.right * bulletspeed;
}```
oh I didn't know that, thanks
do raycasts detect hits if the raycast is inside of an object?
No
is there any solution? because im tryna detect whether the player is touching air or the floor
are you using a rigidbody or a character controller?
Make it not start from inside of object you trying to check?
using a script without physics
with a rigidbody
im trying to detect if the player hops off a platform
i've tried using colliders
but it doesnt really work
if you're using a rigidbody or character controller, you don't need a raycast for ground checks
i dont use gravity
` public UnityEvent<ChatMain> changeText;
public void doSomething(ChatMain chat)
{
Debug.Log("a");
chat.textSpeed = 0.01f;
} ` `
Sorry sent early
rigidbodies have their on various collision check events, best to use them when ground checking
.
i've used them, but is there a specific way to detect if the player is colliding with nothing
I'm getting an error that says "Object of type UnityEngine.Object cannot be converted to type ChatMain
What could be the problem? This is how I invoke it
textState.changeText?.Invoke(this);
this line is on ChatMain itself
bool isTouching = false;
private void OnCollisionEnter(Collision collision)
{
isTouching = true;
}
private void OnCollisionExit(Collision collision)
{
isTouching = false;
}
i have used them
they're currently what im using
but with triggers version
triggers are for triggers, why are you even using them?
your ground won't be a trigger
so your player floats around like an astronaut?
lol okay but these should still work regardless of gravity
should i make the collider extend or just cover the 3d model?
I’m still having trouble with this :,) casting did not work either
Anybody here know where there is any documentation for changing the output device? I'm trying to allow the player to change where they hear their audio (headphones, speakers, etc). I can't seem to find any documentation though
I have a field in the parent class that I want to modify/re-declare in the child class. How can I achieve this?
I'd assume that it's something controlled by the os. Unity can only use whatever the OS gives it.
AFAIK just like with monitors, the Operating System is responsible for that.
You could fix it with C# itself, marshalling the Operating Systems dll's to change it. But take this with a grain of salt, I'm not 100% sure about this either.
You could try using the new keyword in the field declaration.
Gotcha. i've just seen unity games that have options in the settings menu for mic, headphones, etc. figured I'd give it a shot
Yeah I would assume they do it this way. Also, some of the assets on the asset store give you this functionality, if you want to throw money against the problem.
Nah it's something I'd want to try myself if I did it. Thanks though
Doing that seems to leave me with 2 copys of my field in the inspector.
I now have a new question. The field in the parent is marked virtual and the field in the child is marked override.
However I am getting an error, and I suspect it's related to the field being an enum. Is this a common problem?
You can't override fields or make them virtual.
Maybe use an interface property instead and define the field separately in each class.
Why do you need this ?
All class B's inherit from class A. All class A's have a field declared and assigned.
B's need that same field but with a different value.
C's also inherit from A, also needing the field, but don't need it changed.
My field is an enum
But putting a different value isnt overriding the prop. Just set the value you need in a init method, or start or whatever
I need the field settable in the inspector
That would also just work
With which implementation?
The value would be stored in each instance its not tied to the parent class at all
You jest set the value in the inspector.🤷♂️
If you have a serializable public enum in A you can set it to what ever value you want in a instance of B
Ahh, yes of course. Thank you(: Silly me
Is it good practice to create interfaces in their own file, like classes?
Neither bad nor good.
I'd say if the interface takes some space and there's already a lot of code in the file, move it to a different file.
In fact I'd move them to a new file in any case.
I find myself constantly being screwed over by needing icons for things which require me to more often than not create SOs or expose it somehow to the editor just to provide it. In this case I would really just like to define status effects in the code and not have to create assets for each one, but I don't know how to provide the icon then. I've been thinking about creating a global manager that have a bunch of icon properties for icons that are shared across multiple things, such as abilities and status effects for example. However, I feel like this could grow out of control quite quickly and bloat the memory usage since you'd have icons loaded in that aren't used at a particular point in time. I've also tried loading icons from the code from a specific folder using Resources.Load but I found that it's not very reliable since paths and name of icons can change without the code knowing about it.
Do you guys have any alternative suggestions for how I could approach this problem?
public class StatusEffect : ScriptableObject
{
public string statusEffectName; // "name" is already taken by ScriptableObject
public string description;
public Sprite icon;
public virtual void ApplyEffect(BaseController caster, BaseController target) {}
}
[CreateAssetMenu(fileName = "New Bleeding Status Effect", menuName = "Data/Status Effects/Bleeding")]
public class BleedingStatusEffect : StatusEffect
{
public override void ApplyEffect(BaseController caster, BaseController target) {}
}
Yes, it is.
Every file only consists of 1 thing - class, interface, enum, whatever
And the name of the file respresents what that thing is.
The only exception I would name is a simple record type for some obscure behaviour never used again, or File type classes. But neither of those are possible in Unity as far as I know.
It's just way easier in terms of readability, knowing the file's purpose without having to look into it for anything extra. If you have to consider moving it because it might become bigger than what you would accept for some reason, you might as well just put it in that new file.
Awesome, thanks!(:
Is there any way to access the hardware intrinsic leading zero counter inside unity?
All of the ones on the docs require a later runtime version
Do it in a json file maybe
Except stuff like applying the effect can't really be done in it because it's specific scriptable behaviour
The thing with these type of things is scalability, and it is probably a very good idea to just create a seperate file for them should you add more behaviour to it. It's gonna be a lot better than one bloated manager
@thin aurora You mean like I have already done in my example?
Yes
My UI sprites for the individual inventory slots appear nicely in the bottom right, but the same-sized UI objects in the top left appear squished, as if their 9-slicing isn't working or something. Any thoughts?
so a tutorial I am following says this
I have written this. only i have an error over this line and they dont in the video
This is #💻┃code-beginner stuff, and can you show the actual error?
I think I understand what its saying but im confused why it works for him and not me
He made a script named HealthBar before this. This just makes a reference to that script. You currently don't have a HealthBar script, or you named it differently.
That's not related
Your class is not called HealthBar then
now I want to guess its because this script is under a different namespace to the other one?
@rough brook Show code inside HealthBar.cs
Oh, yes. Likely a namespacing issue then
You have it in a namespace
Add using RPG.ui; at the top of the other file
If your IDE is set up correctly you can also press ctrl + . on HealthBar and it should give you the suggestion to add it
If it doesn't do that you need to configure your IDE properly
now I got this. not sure what it means by protection level
Your method is most likely private as it has no access modifier before it
Put public before it
Accessibility modifiers is something you should look into
And maybe continue your questions in #💻┃code-beginner
I hate to say it, but its likely you've followed a tutorial that may have been slightly too advanced. If you feel too lost following the tutorial, I'd recommend learning some C# basics before tackling the tutorial(:
thanks for the help guys. got it working.
wouldnt believe I have been doing this for more than a year on a college course lol
#💻┃unity-talk is the catch all channel when the question doesn't belong in the specific channels. No idea about your SSD though, you can just do a hardware check.
How could i get which button was pressed from a addlistener when the button is in a list of other buttons
Add a tag, unique name or spot in your gameobject hierarchy
Not sure if you can compare the reference, but considering it's done by checking memory (I think?), you could also use a First/Single(OrDefault) on your list
I was tryna a avoid tags but aight
How do I give a father to an object through code?
You mean a parent? Then .parent = something
Also, don't cross post
From the #854851968446365696
ok thanks
yeah parent sounds better anyway i saw somebody else call it father so i went with that
father doesn't really exist in coding, at least I have never heard of it in 20 years.
Its always parent -> child relations
yea same lol
I dont have a problem but I do have a question. my tutor had us learning atan2 for rotation towards an object. Why did learn that if LookAt makes it so simple?
we *
#💻┃code-beginner is probably better for this
thx, i'll copy paste it there 👍
Whenever I use InputSystem.DisableDevice(Mouse.current); the mouse pointer disappears, I can set it visible and it comes back for a period of time but will disappear again eventually. Is that expected behavior? I can still interact with elements in my UI wherever the mouse pointer is even when not visible
It makes better code. Same as any variable, you can pass them around
They are also often used for events
Storing method references in a list for example
Events
Stuff that references a method without invoking it
You can subscribe to a delegate from different places and receive events via them. This way you reverse the dependencies and don't need to invoke methods manually.
atan2 (arctangent with 2 arguments) is lower level and may let you connect what is actually happening mathematically which can be helpful for a better understanding in general, for use in other engines, etc
transform.LookAt is a simple wrapper method to make things in Unity specifically a bit easier
You can use them for callbacks. For example you could have a function like this:
IEnumerator MoveCoroutine(Vector3 to, Action onComplete) {
while (transform.position != to) {
transform.position = Vector3.MoveTowards(
transform.position,
to,
speed * Time.deltaTime
);
yield return null;
}
onComplete();
}
void MoveAndShoot(Vector3 to) {
StartCoroutine(MoveCoroutine(to, Shoot));
}
void MoveAndSpeak(Vector3 to) {
StartCoroutine(MoveCoroutine(to, () => Say("hello!")));
}
oops, i left out the invocation lol
fixed now
I wish I knew about it first. Really confused why I wasnt taught something that simple before moving on to atan which seams more complex
Ask your teacher why
waiting for a reply
depends on your level and background really - I'd be pretty wary of a course that felt teaching me a specific method for a specific version of a specific engine was a worthy thing over a fundamental concept in programming/mathematics that would be applicable anywhere
Maybe they taught you atan first hoping that you'd discover LookAt on your own
who knows but pretty annoyed considering it wasnt revealed even as I was clearly struggling
is what it is. I have come out the situation knowing
I'm sure you can appreciate that the easiest way to do something, that obfuscates/hides the detail, isn't necessarily in line with helping you have the best understanding and coming away with the best education though
sometimes it makes sense if the simple thing is a building block towards the harder thing, but sometimes it can actually be the opposite and make it harder
sure but if I dont understand the simple, its strange to learn the complex, I would think
That velocity calculation is unreadable!
var speed = (isCrouching, isZooming) switch {
(true, _) => crourchWalkSpeed,
(_, true) => zoomWalkSpeed,
_ => walkSpeed
}
var velocity = new Vector3(
currentDir.x * speed,
velocityY,
currentDir.y
);
characterController.Move(transform.TransformDirection(velocity) * Time.deltaTime);
Longer but at least it makes sense
my tutors response was that trigonometry and pythagoras are important to everyday life not just within coding
perhaps - learning can be hard, some of the best things I've learnt have been from not having the slightest clue how anything works while staring at a page in complete confusion for days
lol
what the hell are they doing every day
"useful for measuring things around the house"
but you try things out, experiment, figure small details out, and at a certain point it can click and you have a fantastic platform of knowledge to build on
water surface, here's a pastebin of the buoyancy code to make it clearer: https://pastebin.com/CSjpjYwz
Is it not world space and object space?
these kind of names always lead to confusion
hiya! i was wondering if i could get some help on writing a script? i'm trying to understand how instantiate works atm, and want to know if i could use instantiate to spawn prefabs to the right of the player.
Instantiate creates a copy of the object you pass to it.
typically a prefab
everyday may be a stretch, but one of the biggest things you learn from mathematics in general is confidence & competence in calculation and general problem solving - having a solid understanding of trigonometry and geometry in general really can help with your intuition in every day life - you wont sit down with a pencil and start calculating a hypotenuse like you would in school, but you will intuitively understand a diagonal is longer, and about how much longer, etc
private void Spawn()
{
if (Input.GetKeyDown(KeyCode.E))
{
Instantiate(ladderPrefab, player.transform.position, Quaternion.identity);
Debug.Log ("E key was pressed.");
}
if (Input.GetKeyDown(KeyCode.Q))
{
Destroy(ladderPrefab.gameObject);
Debug.Log ("Q key was pressed.");
}
}```
i've got this atm, is there anything wrong with it so far?
```cs
// format code like this
```
// format code like this
mb!
What is InstantiatePrefab?
cs on the same line as ```
ack
What is InstantiatePrefab?
then what is the problem?
the prefab doesn't spawn whenever i press E
@serene egret if you're making mistakes like that, it sounds like your IDE isn't configured. You should set it up using the guide in #854851968446365696, then it will autocomplete the correct name.
appreciate it!
The test for whether E is pressed should be in Update
Or you can call this function from Update
Where are you calling it?
Destroy(ladderPrefab.gameObject); is an error. This is trying to destroy the original prefab asset, not the copy you created.
How do I convert X value and Y value from a string to an Vector2INT? For instance lets say I have string and its value is "X20Y10". How do I convert it to a Vector2INT?
ive put the code into update so now that its formatted like this
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
if (Input.GetButtonDown("Jump") && IsGrounded())
{
jumpSFX.Play();
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
UpdateAnimationState();
if (Input.GetKeyDown(KeyCode.E))
{
Instantiate(ladderPrefab, player.transform.position, Quaternion.identity);
Debug.Log ("E key was pressed.");
}
if (Input.GetKeyDown(KeyCode.Q))
{
Destroy(ladderPrefab.gameObject);
Debug.Log ("Q key was pressed.");
}
}
is there a way i could use instantiate and key inputs to spawn prefabs instead of deleting the original prefab i already have in the scene?
for e.g. say the scene doesn't have the prefab, the key inputs would be responsible for spawning and deleting them
If you know for certain that the string will always be in this format and you don't need to be able to handle incorrectly formatted strings, all you need to do is find the index of the 'Y' character and then you can extract the substrings for the two numbers.
The X value will always start at index 0 and go up to where the 'Y' character is. The Y value will always start after the 'Y' character and go up to the end of the string. Then you can use int.Parse on those strings.
lots of different ways to do this, you could parse by character, use split/replace operations, substring by index - personally I'd just default to using a Regex expression and extracting the numbers into a MatchCollection, e.g \d+ will match any number of digits
What should happen if the user presses E multiple times and spawns multiple ladders, and then presses Q once? Which ladder should be destroyed?
to be honest i only want the user to be able to spawn one ladder at a time
whenever searching up how to code a toggle function
instantiate is what came up so i've been fiddling with that so far
thanks for the refactor! that made the code a lot cleaner, but the issue still persists. i'll attach a video of what i mean to hopefully explain it further.
same deal, removing the gravity removes the issue here, but that's not a solution.
Thank you, ill check it out
is there a way to get it from the addlistener, or something without having to use tags or add anything to each object? It’s just there’s quite a few buttons in the list
Oh wait i do have a unique name
How would I see if it was the one that was pressed though
I'm making a game in VR where you are flying on a magic carpet, i want to grab the air in VR and make the carpet follow my hands rotation
Any idea how?
How can I generate a Mesh with multiple materials? Specific areas/quads of the mesh will have a different material
pass the button through a delegate
the VR controllers will be mapped to a GameObject for each hand, possibly varying in structure depending on the exact VR framework you're using - movement/rotation can simply use the position and rotation of those objects. You could also look into using the input axis deltas directly, but just building on the framework is probably easier
idk how delegates work
Watch this video in context on Unity Learn:
https://learn.unity.com/tutorial/delegates
Delegates are containers for methods (functions). They can be thought of as a variable that be called like a function to invoke whichever methods are currently stored in it. In this video you will learn to make your own delegates and use them to call various ...
will this teach me what i need, to do what i’m trying to do?
hmmm, I'll give it a try, but won't it bug out if it will look at both controllers at the same time?
maybe. what do you need to do with the button
I just need to get what buttons being pressed when the addlistener is called
possibly - you'll need to implement something and iterate on it to behave how you want
I have a inventory system, and when one of the slots is clicked i want it to drop the item
are buttons in a list ? just pass the index no?
That's the tricky part
Yea the buttons are in a list, I’ve thought about that but how do i pass the index when the addlistener is called, i have a for statement iterating through the list putting the addlistener on each button
ehh.. that's why I told you about delegates xD
Alright and that video will show me what i need?
yes, but that's where a lot of the problems with VR come in - user interaction is different, two free controllers and headset, each with separate position and rotation, are a novel input system and figuring out how to utilise that for interesting gameplay is basically what VR development is all about
look at the example here as well, you see you can pass params and whatnot
https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Button-onClick.html
I'd start by trying to implement something that is line with what you want, using simple gameobject tools you're familiar with, and then come back with specific questions if it's not working how you want it to
How do I use the delegate with my script to pass which object is pushed though
the same way the examples on the page show you how to pass params
Ok i think i’ve got an idea
would still really appreciate some help with this, i'm honestly stumped and barely know where to even start with solving this.
there is literally what u wanna do on the site cs void ButtonClicked(int buttonNo) { //Output this to console when the Button3 is clicked Debug.Log("Button clicked = " + buttonNo); }
Using the third option and passing which index it’s on in the list would work right?
Alright that’s what I was thinking thanks
yes , Button is a type and could be passed as well
Anyone know how this can happen? 😵💫 And how to make sure it doesn't happen again..
What is "this" which you want to stop from happening
If you see the image, one image is when clicking on a prefab in inspector, and the other when opened in prefab editor. So there is information that doesn't seem to be serialized correctly. I've had this on a few of my prefabs. I've resorted to recreating the prefab and it has solved it for now.
Is this a prefab variant?
Yes
The image on the right really seems like it's not the prefab itself but an instance of the prefab 🤔
Mostly due to this
oh wait nvm
I see
Got a little confused with the naming.
Is the field in question properly serializable?
Are you using Odin Serializer or anything?
Yes, Yes
Hello guys im beginner here
im casting a raycast downwards in front of my player to check if there is a drop. If so, I disable the input vector2 completely (so he can't walk off ledges). However, if I am say running diagonal towards that ledge, he stops dramatically, whereas it should allow movement ALONG the ledge, just not straight off. Any idea how I would go about that? I take it involves disabling the input vector x or y that relates to the direction the ledge is in, but not sure where to start
I wanna ask. How to make when the bird hits pipe then scene change to restard the gam?
it's a multi-step problem so split it in pieces:
-Make a function that restarts the game (reloads the scene)
-Use colliders to detect collision between the bird and the pipes
also this is #💻┃code-beginner question
you have to give more context, it's hard to say what ledge even is without knowing what type of game/prospective you're working with
in 3d space, but controlled from a top down style. A ledge meaning any kind of sheer drop. I dont want to create invisible walls all around my map I'd rather do it via code
basically this: https://stackoverflow.com/questions/73582666/unity-blocking-character-from-walking-off-ledges
I don't think a single raycast is enough information for this kind of thing
honestly this is prob the best solution that comes to mind
anything else will be extremely complex and not counting for edge cases
just my 2cents
i've got a single one in front, and i guess I need at least one at the front left and right as well. So if the front detects a drop, check either side and steer the input vector towards that
literal edge cases 🤣
disabling movement is an ugly way to do it
any way to alter the movement vector2 I wondered? the drop will be at player.transform forward
would it really be that much to add invisible colliders, how many ledges do you really have
well some levels are using terrain and drops all over the shop
+1 for invisible collider
probuilder has literally a drawing tool
put the view Top down
and draw a giant thing around the egdes
I have been doing invisible colliders, but what about procedural levels, would have thought there would have been a way to do it somewhere online lol
Invisible Collider can be done in procedural generation
ofc its possible, anything is. it's just gonna be lot of math to deal with and consider all possible vectors which player will hit ledge from
good point
colliders are way easier
need help
Is it just me, or is probuilder really weird to use?
No it's not, also not a code question. #🛠️┃probuilder
well I just wanted to discuss it
not like you are forced to either ask or respond to questions here right
Hi, I would need a bit of help figuring out the following (in 2d): Let's say I have a player and a tree (static object). Both have rigidbody2d and a collider (non trigger) attached to them. How can I make such that a player can pass through another player, but not through a tree. At the same time player x player collision or player x tree collision would take place.
use the collisions matrix in the physics 2d settings
I have tried it, but I can't "uncheck" player x player layer collision because I need them to take place
what is your goal?
how many players are there
Does it matter a lot? If so then suppose there is a max of 40 players in a scene. Otherwise we can just take 2 players
(the game is planned to be multiplayer)
I have tried it, but I can't "uncheck" player x player layer collision because I need them to take place
are you trying to say you need to know when players hvae collided, but you do not want them to push each other physically?
create a hierarchy with a separate player trigger layer and player layer
yes
could you expand on that?
Player (layer=Default)
TriggerCollider (layer=Triggers)
PhysicsCollider (layer=Players)
oh I see how this can work. Will try it out. Thanks!
generally, for platformers, you can't use rigidbody physics for movement
oh really, never tested that :D
you can explore corgi engine 2.5d for ✅ multiplayer ✅collide and slide physics
if you want your movement to be traditional platformer movement
you will not be able to use rigidbody physics for it
does that make sense?
Hello, Just want to ask why my BoxCast also detect the object behind of the other object with same layer? I only want to detect on whose in front or above
my game is not a platformer though
it will detect whatever the first object is that it hits
it's just topdown
In brief, moving a circle shaped player in x, y and rotating that circle in z
i see. you can look at the moremountains topdown engine
which also has multiplayer
topdown movement has many fewer traditions
but i'm not sure you want to be futsing about with this stuff if it's already all made in an asset
Thanks for the suggestions, I thought of using Unity's multiplayer
if it's topdown
you should be working in the xz plane, not the xy plane
i think you should look at this moremountains top down engine asset
really depends what your goals are
I have an instance where it also detect what's behind of it, not sure if its because my collider are thin
can someone explain to me why the interactUI isn't being turned on?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OpenInteractAbleUI : Interactable
{
[SerializeField] private GameObject interactUI;
[SerializeField] private bool isTutorial;
[SerializeField] private TutorialCreator tutorialCreator;
//this is the base interaction for this object
protected override void Interact()
{
interactUI.SetActive(true);
Debug.Log(gameObject.name + " Trying to open");
if (isTutorial)
{
if (tutorialCreator.seeChallenges == false)
{
tutorialCreator.seeChallenges = true;
tutorialCreator.CheckTutorials();
}
}
}
}
I'll take note, thanks again
Does the information saved with PlayerPrefs persist between updates of an android app?
If yes I have a problem: I have changed the format of the data structure with which this information is saved.
Any suggestions for how to handle this breaking change?
wdym by "also"? How are you getting more than one result?
Any suggestions for how to handle this breaking change?
you can read about the general programming concept of migrations.
so, is that true what have i said?
Does the information saved with PlayerPrefs persist between updates of an android app?
yes
It should be only detecting "Card (3)" which on the top but it also detect the ones that is behind of it, check the debug
you can set a debugging breakpoint on the interactUI.SetActive(true) line and see what happens
you'd have to show where the raycasts are originating etc.
those cards are splayed out in a way where the top of the bottom card is exposed for example
your boxcast could just be hitting that
its fine its been fixed now thanks anyway
how to share a code again? like the shortcut?
private void Update()
{
if (isDragging)
{
RaycastHit hit;
bool isHit = Physics.BoxCast(transform.position, scaleCard / 2, -transform.up, out hit, transform.rotation, m_MaxDistance, Layer);
if (isHit)
{
Debug.LogWarning(hit.transform.name);
OnTopOfCard = true;
Target = hit.transform.GetComponentInParent<Card>().Tail;
}
else
{
OnTopOfCard = false;
Target = null;
}
}
}
I recommend using the physics debugger to visualize your boxcasts
Window -> Analysis -> Physics Debugger
okay, thank you
// Assume item is correctly built
Item item = new WoodItem();
if(item == null) {
// Case is returning true even though item should not be null
}```
This is basically my issue
This happens when I derive my Main ITEM(abstract) class from MonoBehavior.
WoodItem is dehrived from Item
You cannot create MonoBehaviours with new
So I have an issue, this code is suppose to only run once, with the oneTime bool, but it still runs every frame and it spits out an NullReference Exception. Can anyone see what it is I'm missing?
Here is the code:
if (scene.name != "StartScene" && oneTime == false)
{
slider = null;
slider = GameObject.FindGameObjectWithTag("Slider").GetComponent<Slider>(); //NullReferenceException here
slider.value = startVolume;
oneTime = true;
}
the fact that it's spitting out the exception means oneTime = true; is not running
you need to fix the exception
yes, but how?
NREs are easy. Figure out WHAT is null
and fix it
in your case either GameObject.FindGameObjectWithTag("Slider") is returning null OR the returned object doesn't have a SLider component on it so GetComponent<Slider> returns null
DO you actually have an:
- active object
- with the tag "Slider"
- with a Slider component on it?
in the scene?
At least one of those three things is missing
The gameobject is not active when you load the scene, and the NRE disappears when you activate it
Does that have anything to do with it?
yes
that would be the first thing I mentioned
- active object
FindGameObjectWithTag only finds active objects
ah sorry, i see, but how do i do it with inactive objects?
is there an alternetive to make a ~class~ instance deheriving from it without having it in the scene?
FindObjectsOfTypeAll works on inactive GameObjects
If you don't intend on attaching your class to a GameObject as a component, don't make it a MonoBehaviour
I think the better question is why are you using FindGameObjectWIthTag in this situation at all? Do you have a good reason?
Can you not just directly reference it?
I was going to have it be atachable but, I guess I have to figure out a work around for my sulotion, thanks for the help!
Maybe if you explain what exactly you're trying to do, we can suggest something.
I don't have time ow but later I'll try
im getting this error message,
'Health' does not contain a definition for 'fillAmount' and no accessible extension method 'fillAmount' accepting a first argument of type 'Health' could be found (are you missing a using directive or an assembly reference?)
and the code i have is,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
[SerializeField] private Health playerHealth;
[SerializeField] private Health totalHealthBar;
[SerializeField] private Health currentHealthBar;
private void Start()
{
currentHealthBar.fillAmount = playerHealth.currentHealth / 10;
}
private void Update()
{
currentHealthBar.fillAmount = playerHealth.currentHealth / 10;
}
}
i've been trying to find the problem for a while now, but no luck. can anyone see where i've gone wrong?
Did you define anything called fillAmount on your Health script?
My guess is you actually meant to use Image instead of Health for those fields, no?
i haven't no

should i?
it's not making sense i'm so sorry 
There's nothing called fillAmount on Health right?
So why are you trying to use such a thing?
You can't use things that don't exist
[SerializeField] private Health playerHealth;
[SerializeField] private Health totalHealthBar;
[SerializeField] private Health currentHealthBar;```
see these?
You've defined them all as type Health
so if you do currentHealthBar.fillAmount it's looking for a fillAmount property from the Health script
which doesn't exist
hence the error
I'm guessing what you MEANT to do was:
[SerializeField] private Image currentHealthBar;
Image DOES have a fillAmount:
https://docs.unity.cn/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.Image.html#UnityEngine_UI_Image_fillAmount
by changing the fields Health to Image, i'm getting the same console error.
what console error
show the new code
show the new error
also make sure you saved your changes.
Hello! I would like to copy a unity native class and make my own variation of it. I copied the entire native script into a new one and named the class differently. It throws a bunch of errors at me. Any idea why? The most common ones are:
"must declare a body because it is not marked abstract, extern, or partial Assembly-CSharp, Assembly-CSharp.Player"
"The type or namespace name 'Orientation' could not be found (are you missing a using directive or an assembly reference?)"
The weird thing is, even if I went and fixed those erros, why do they pop up in the first place, when they work just fine in their original script?
You can't copy unity native classes really
there's a whole C++ side to them that you don't have
what are you trying to do?
the changes ive made were
[SerializeField] private Health playerHealth;
[SerializeField] private Health totalHealthBar;
[SerializeField] private Health currentHealthBar;
to
[SerializeField] private Health playerHealth;
[SerializeField] private Image totalHealthBar;
[SerializeField] private Image currentHealthBar;
and the console error didn't show up anymore.
turns out it was just a problem on my behalf sorry sorry
its a bit hard to explain so let me phrase it like this: As a unity developer I want to create an editor with a graph view that can make use of nodes. Those nodes have Ports, but the native Unity version of those ports are not working like I need them.
So my first thought was to make my own Port. inheriting from the same master class as Port, copying the script and adjusting it as I see fit.
What's the limitation with GraphView that you want to work around?
also #↕️┃editor-extensions is probably the best place to discuss GraphView
GraphView.Port has the following things that misfit my usecase:
- ports are either "in" or "out". I dont need a flow in my graph view, I just need connections. (A is connected to B), without any direction
- aesthetically: orientations. They arrange the connecting lines in a way that looks fine for a classic node flow, but Id rather have them go straight from A to B. Also I want to decide on the color of those ports.
- the Port name is a string, I need it to be an inputfield
thank you, I will go there
Ok, so my issue is that my fields do not show up in the Inspector despite having the SerializeField attribute. (They show up in the debug but not the normal one)
This is the class in Question and it's fields (excluding methods as they are irrelevant.)
public class StateSwitchButton : NetworkButton
{
[SerializeField] private Sprite enabledSprite, disabledSprite;
[SerializeField] private Image enabledStateImage;
[SerializeField] private bool defaultEnabled = false;
[SerializeField] private UnityEvent onEnable, onDisable;
private bool isEnabled;
}
And the class NetworkButton which it inherits from looks like this (excluding methods once again):
public abstract class NetworkButton : Button
{
public static readonly List<NetworkButton> buttons = new List<NetworkButton>();
}
I've read somewhere that in some cases inheritance breaks the inspector, which would be a serious issue as the inheritance is required unless I pull out some workarounds.
This happens to every class inheriting from NetworkButton btw.
Are you deriving from UnityEngine.UI.Button?
Yes
That class has a cusotm inspector
so it's drawing with that custom inspector
which is why your fields aren't showing
It worked before, it just stopped for some reason yesterday, I guess I'll have to write a custom inspector to override it, great.
example^
Thanks, I'll check it out.
how to handle screen and sprite sizes in a 2d game for mobile?
https://gamedev.stackexchange.com/questions/79546/how-do-you-handle-aspect-ratio-differences-with-unity-2d I have found this, but maybe it's outdated
first time playing with mobile
Sorry for the late reply, had to go quickly, but yes the script is attracted to gameobject on another scene, and is set to dont destroy on load, and this is the part where i get the new slider in the new scene, this was just the quickest way i could think of, but please tell if there is a better way
Could use the singleton pattern.
I haven't used those before, but i'll look into it, thanks
hello, can anyone tell me why i am getting this error?
i had ml agents 1.0.8 package installed and i updated it to 2.0.0 and then that error appeared
is it preventing you from compiling or play testing?
yes
Right so i looked into it a bit, but I'm unsure how i would go about linking the new slider to the script once i load the new scene...
you'd just access the singleton wherever you need it:
MySingleton.instance.whatever```
that whatever could be a reference to your slider
or a function that disables the slider, whatever you want.
try reinstalling the package or something as that error is quite vague, just means it’s can’t find a file
ohh, you mean to make the slider object a singleton?
whatever you're trying to access easily, yes
i did, its still there
ahh, okay i see, thanks
Does someone have an idea why the editorloop keeps spiking every second on the playerloopcontroller? Some issues mentioned opened asset store window but I set the view back to default and it keeps happening
Is it causing issues?
Yes, sometimes it causes a little stuttering. It’s a high end pc so there seems to be a problem somewhere
You could try enabling "Deep Profile" and "Call Stacks", then expanding where it says "No Details" in the bottom right to show more details and run the profiler again - itll consume more RAM, but will also let you dive deeper in the raw hierarchy so you can (hopefully) see what Unity is actually trying to do during those spikes, then you can loop up those specific calls on Google, if they are documented it could give you a good indication of what it does, if not, maybe youll find a forum post about it, otherwise you may be left to investigation and trial/error (disabling certain editor windows one by one until you notice a difference)
is it possible to adapt a minimap render texture camera to make it look something like this? I can understand how to do the icons easily, but I guess it would be a lot of work for walls? I was wondering if its possible to only render specific textures on layers, eg the floor textures and block everything else out, so the minimap will resemble the level layout
Thanks, will try it out
you can use a camera's culling mask to only render certain layers
I'm having a hard time creating an Asset Bundle. Whenever I attempt to create the asset bundle, I get an error are you missing an assembly reference? My prefab uses scripts that reference a package (https://github.com/Unity-Technologies/com.unity.webrtc), but I'm unsure on how to include the namespace from that package.
I get an error are you missing an assembly reference?
If this is a compile error you should share the full compile error and the code that causes it.
Yes, so I have got that package working, but when I try to make my prefab into an assetbundle I get an error
My code and the package work until I attempt to build the asset with the asset builder browser/script:
(https://docs.unity3d.com/Manual/AssetBundles-Browser.html)
If I build to exe or android app, everything is fine
I want to use my prefab as an asset bundle in another project
error CS0234: The type or namespace name 'WebRTC' does not exist in the namespace 'Unity' (are you missing an assembly reference?)
on what line of what script
the full error message
D:\Github\DesktopVisionUnityPackage\Runtime\Scripts\DVConnection.cs(2,13): error CS0234: The type or namespace name 'WebRTC' does not exist in the namespace 'Unity' (are you missing an assembly reference?)
Is DVConnection your code?
Yep
Do you have an asmdef?
I don't know
You don't know?
Check
it's an asset, in your asset folder. Assembly definition file
I do not appear to have one
webrtc does though
Their asmdef is listing specific platforms for the assembly to exist
I'm not sure exactly how asset bundles work but... seems like their assembly is not included when building the bundle
Hmmm
I'm learning about the asset bundle right now, so I can't say for sure lol. Been running into issues immediately
but I believe so
"Build Target"
whats in advanced settings
this is what I see when I open the Unity Asset Bundle Browser tool
A bunch of errors after I attempt to build (from missing unity.webrtc)
Anyone has any idea how to save a GameObject that was created in PlayMode along with all its components? I was taking a look at this https://github.com/inkle/Unity-Save-Play-Mode-Changes/blob/master/Assets/PlayModeSaver/Editor/PlayModeSaver.cs but holy shit his code is dogwater
cheeky way is ctrl+C it in play mode
then paste in edit mode
yeah, but i want my tool to be seamless.
you can just write it to an asset in code
you can? what's the API
ok lemme try
FUCK it works
thanks alot. i wish i knew this earlier. there goes 5 hours :c
Does anybody know why im getting these errors when i try to build my game?
One of your scripts references Editor stuff, it's not possible in a build.
You'll need to exclude it from the build (put it in an Editor folder for example)
I made a function, for my player mouvement (first person), It works but I think their are some big problem on it ? Would someone be available to help me fix/review it in a quiet place ? ❤️
I would like to have a good base to start my project.
You can create a thread if you're afraid more conversations would bury your questions
Is using "UnityEngine.EventSystems" Editor stuff?
No, anything under the UnityEditor namespace
so it needs to say Using UnityEditor
Yes
ohh i see, that weird, i dont even use that, anyways thanks a lot
question so i've been creating new scriptable objects in runtime via constructor rather than create instance function. Is there issue i should worry about for continuing to do it this way?
Hello can someone help with Rotations,
I want to rotate Car's shadow (plane) according road's Normal (Raycast). shown in GIF (20mb can take some time to load)
Rotation along Axis Z and Axis X works as i wanted, but i can't find how to make axis Y repeat after RayCast (Car) gameObject rotation. thx
From what I'm reading you need to use CreateInstance because if you use new, then Unity won't be able to call its special methods like Awake or Start
Would there be a good place on the discord for that, or would you recommend a particular place ?
so this will affect all scripts with start and awake or just the scriptable objects?
If your question is about code, any of the 3 code channels will do (depending on how difficult you evaluate your question)
Else, see #🔎┃find-a-channel for the channel list, and create a thread in the most appropriate one.
Just the SO instance. Sorry I phrased it badly
[...] then Unity won't be able to call the special methods like Awake or Start, on the SO instance.
Is there a channel with people looking for partners/teammates? (sorry if this is the wrong place)
Collab requests should be made on the Forums indeed
oh ok thanks
hi all, i've added movement, but i'm getting stuttering when moving. the stuttering also seems a bit random and not really at specific points each time. why might this be?
video: https://streamable.com/gfsxrb
the way i'm doing it basically has each tile as a cube object and i'm re-parenting the character object into each tile along the way. i then have an Update() on the character object to do a MoveTowards localposition of 0, 0, -2 (to stand on top of the tile). the re-parenting is part of a co-routine.
- pathfinding finds a specific ordered list of tiles to move through, to avoid objects
- re-parent the character to the next tile, delay, repeat til the end
- meanwhile as above ^ : keep updating the character's local position to 0, 0, -2, with MoveTowards
i've also tried it with packing the movetowards into a while for when the position isn't equal to the target.
both codes here: https://pastebin.com/2si5Vk74
didn't know they can use awake and start that said for the objects in question i guess it's better to do it via constructor
for me at least since i need to not only create it but also create it based no parameters
still glad to know there's no major ramification for doing so
I would still use CreateInstance myself though. If you choose to use new test thoroughly especially in a build, where their "save" behavior is different
Does this also apply to Destroy() ?
You can't Destroy a ScriptableObject instance because it doesn't live in a scene
ups i overlooked that you were talking about scriptable objects
It just jumped out at me since i had struggle destroying an object which i created through a "regular" c# class
You can Destroy SO. Like how you destroy Sprite or Material. It's cleaning up C++ side resource of UnityEngine.Object
How would I paint mesh objects into the scene with a brush?
Basic First Player Camera/Movement Debug/Review
use a tilegmap grid
How do I make Rider stop preferring System.Numerics?
Whatever you use more will become prioritized.
Can I make it forget
I've not once used Numerics on purpose
looks like they're using machine learning for the suggestion order
😢
Ahah
I updated to 2022 and I've notice that annoying feature. It also automatically inserts namespaces if I accidentally tab to their suggestions
Unchecking "Sort completion suggestions based on machine learning" fixes it. Go away silly machines
Hmm, mine is disabled for C#, but I've never seen this setting.
Maybe because you upgraded from an earlier version
I have a fresh install, guess it's defaulted on now
seems to work now
I'm still getting AI assisted recommendations on a new line even after disabling though, there's a cache somewhere and I don't feel like hunting that down Nevermind restarting visual studio cleared it
(I'm talking about Rider btw)
They both have machine learning assistance
i get following error trying to set up velocity over lifetime of my particle system:
Particle Velocity curves must all be in the same mode
Code:
var vel = children.GetComponentInChildren<ParticleSystem>().velocityOverLifetime;
//vel.space = ParticleSystemSimulationSpace.Local;
AnimationCurve curve = new AnimationCurve();
curve.AddKey(0.0f, 1.0f);
curve.AddKey(1.0f, 0.0f);
vel.y = new ParticleSystem.MinMaxCurve(-180 * Throttle, curve);
vel.x = new ParticleSystem.MinMaxCurve(0,0);
vel.z = new ParticleSystem.MinMaxCurve(0,0);
Can someone help me here?
After testing, you need to set the velocity to use curves. Just pass in a curve with 0 key and value if you want it to be zero and it will change it
i just got it, i simply didnt pass a curve but two times a value
vel.x = new ParticleSystem.MinMaxCurve(0, new AnimationCurve());
vel.z = new ParticleSystem.MinMaxCurve(0, new AnimationCurve());
``` something like this would work too
but I'm not sure if that would use a default set by you or an actual empty curve
There is a small purple button at the bottom-left of the code view, you can control it from here
thanks!
My android performance feels a little sluggish. Is there any unity functionality/libraries/api to get the framerate on Android (or any) device? Or do I need to roll my own and count updates?
You can remotely profile it
using the unity editor
Hm, I haven't done that before.. I'll try, though. My own personal phone does weird shit when I try to put it into debug/usb mode (spam disconnects/connects in windows), but I was more hoping to start by verifying that the framerate is <60 or <30 or whatever the target framerate is for some of my team's devices.
I have limited experience working with navmeshes. is there a way to only have an agent move towards the target if the target is within a certain distance of the agent? it's a zombie horde game so i don't wanna check that on too many zombies at once in update because it might affect performance.
use a trigger collider to detect when something is in range
How do you all manage your events?
For a brief example, let's say I had:
public class ShootController : MonoBehaviour
{
public delegate void OnPlayerShoot();
public static event OnPlayerShoot onPlayerShoot;
public void OnShoot(InputValue _) // Using Unity's Send Message Input System
{
// shoot bullet code.
onPlayerShoot?.Invoke();
}
}
public class CameraShootEffect : MonoBehaviour
{
private void OnEnable() => ShootController.onPlayerShoot += CameraShake;
private void OnDisable() => ShootController.onPlayerShoot -= CameraShake;
public void CameraShake() => Debug.Log("Shake camera");
}
In order for this to work, I would have to drag the CameraShootEffect.cs onto an empty object in the scene. So do you just create like a DDOL EventManager empty GO, that holds all your event data? Or what's a manageable approach to this?
Well the camera shoot effect script here seems like it should be attached to the camera
In that vein, I attach event listeners local to where their effects will be
Awesome, thanks Praetor. Yeah, that makes complete sense, I kinda rushed the question out while it was fresh in my mind lol
Another example: a UI health bar could listen for HealthChanged events, and would live on the health bar ui
My events are on the Controller script of an object. If that object has components which are local functionalities, they'll call a function on the controller to call the event.
That way everything outside the controller only has to deal with that controller.
Makes complete sense.
So I've this OnEnable
private void OnEnable()
{
buttons = GetComponentsInChildren<Button>();
for (int i = 0; i < 2; i++)
{
buttons[i].onClick.AddListener(() => Modify(buttons[i], Variable.Volume));
print($"Index: {i}, Button:{buttons[i]}");
}
for (int i = 2; i < 4; i++)
{
buttons[i].onClick.AddListener(() => Modify(buttons[i], Variable.Level));
print($"Index: {i}, Button:{buttons[i]}");
}
}
Which prints out the appropriate assigned buttons just fine. But when I run print(Array.IndexOf(buttons, button)); (the first line within Modify) it gives 2 for the top 2 buttons and 4 for the bottom 2 buttons. Any ideas as to why this could be happening?
The expected result is that it'd give 0, 1, 2, 3, respectively, unless I'm misunderstanding the use of print(Array.IndexOf(buttons, button));
Replacing print(Array.IndexOf(buttons, button)); with print($"Array number: {Array.IndexOf(buttons, button)}, Button: {button}"); explains it, it's associated with the wrong GameObject, though I'm still not how because this code seems fine?
Ah
I've had this same exact issue before
Doing this instead of the other fixes it
private void OnEnable()
{
buttons = GetComponentsInChildren<Button>();
for (int i = 0; i < 2; i++)
{
int j = i;
buttons[j].onClick.AddListener(() => Modify(buttons[j], Variable.Volume));
print($"Index: {j}, Button:{buttons[j]}");
}
for (int i = 2; i < 4; i++)
{
int j = i;
buttons[j].onClick.AddListener(() => Modify(buttons[j], Variable.Level));
print($"Index: {j}, Button:{buttons[j]}");
}
}
I don't know why, but it does work, and that's how I've fixed a similar issue in the past as well, which this idea was given in the first place there at that point
If someone could explain why that is how that works though, that'd be great
lambda variable capture
yes this
Here's my explanation on the forums: https://forum.unity.com/threads/adding-listeners-to-an-array-of-buttons-not-working.1165825/#post-7471571
My more detailed explanation: https://help.vertx.xyz/programming/specifics/anonymous-methods-and-closures
Thanks! I'll look into it!
Oh wow this explains it so well
I get it now, thanks a bunch!
(I did also look at this one, so thanks for that :) )
If you do have things that act weird that you can condense to a plain C# example https://sharplab.io is a great resource
Hello got a little problem, here. I don't know why (my gun) the children of my player is moving away from me when I am moving/rotating Camera.
i need help
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
public class TwoHandGrabInteractable : XRGrabInteractable
{
public List<XRSimpleInteractable> secondHandGrabPoints = new List<XRSimpleInteractable>();
// Start is called before the first frame update
void Start()
{
foreach (var item in secondHandGrabPoints)
{
item.onSelectEnter.AddListener(OnSecondHandGrab);
item.onSelectExit.AddListener(OnSecondHandRelease);
}
}
// Update is called once per frame
void Update()
{
}
public void OnSecondHandGrab(XRBaseInteractor interactor)
{
Debug.Log("Grab");
}
public void OnSecondHandRelease(XRBaseInteractor interactor)
{
Debug.Log("Grab release");
}
protected override void OnSelectEnter(XRBaseInteractor interactor)
{
Debug.Log("First Grab");
base.OnSelectEnter(interactor);
}
protected override void OnSelectExit(XRBaseInteractor interactor)
{
Debug.Log("Exit Grab");
base.OnSelectExit(interactor);
}
public override bool IsSelectableBy(XRBaseInteractor interactor)
{
bool isalreadygrabbed = selectingInteractor && !interactor.Equals(selectingInteractor);
return base.IsSelectableBy(interactor) && isalreadygrabbed;
}
}
it says no suitable method to override but there is
need to see XRGrabInteractable
wdym
also use a pastebin site instead of taking the entire screen
eh true
but wdym\
Nevermind, looked it up myself. Make sure you spelled everything correctly
and you'll be fine
thanks
but
i cant find any mistakes
