#💻┃code-beginner

1 messages · Page 369 of 1

wanton crater
#

oh

#

but ive alwyas had spaces in my file names before

#

and never got this error

#

why do i get it now

halcyon geyser
#

File name

public class ClassName
wintry quarry
#

Maybe those other files didn't have MonoBehaviours

wanton crater
#

im so confused i removed the space now it works i readded the space and it still works

halcyon geyser
#

Till you rebuild ur project

spiral narwhal
#

When I extend Button, my serialised fields do not show up in the inspector

frank zodiac
#

how do i get all children of a gameobject then iterate through them?

spiral narwhal
#

But I would rather cache the objects you want

frank zodiac
#

wait how can i apply all the children of a certain gameobject to an array?

#

do i use .Add

spiral narwhal
#

An array is of a fixed size

halcyon geyser
#

.Add would be for a list

spiral narwhal
frank zodiac
spiral narwhal
#

I would honestly watch some beginner C# videos first

#

That's like basic computer science

#

But you could use a list

frank zodiac
#

strange

frank zodiac
spiral narwhal
#

Then refresh it

#

Haha

halcyon geyser
#

These are very basic things

#

List and arrays arent just for Unity

karmic kindle
#

How do I get the camera to move forward the direction it's facing? This code takes mouseinput and calculates "dragging" on the screen, but it doesn't change the direction when I rotate the camera

    {
        // Determine how much to move the camera
        Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);
        transform.Translate(new Vector3(offset.x * PanSpeed, 0f, offset.y * PanSpeed), Space.World);
        // Cache the position
        lastPanPosition = newPanPosition;
    }```
wintry quarry
#

But also your offsets are in viewport space??

swift crag
#

yes, these spaces are incompatible

#

if you want to move the camera in world space, then you'd better compute positions in world space

#

It'll happen to work if the camera is pointing in the +Z direction

#

but only until the camera rotates

wintry quarry
#

That screentoviewportpoint call is really sketchy. It's supposed to take a position but you're giving it an offset

swift crag
#

indeed -- it's ScreenToViewportPoint, not ScreenToViewportDirection.

#

so it's also wrong if the camera has moved at all

#

although, actually, it's going from screen to viewport space

#

it'd blow up entirely if this was world to viewport space

languid spire
#

this looks like AI code, so of course it is crap

karmic kindle
swift crag
#

that'd still be the wrong coordinate space

karmic kindle
languid spire
wintry quarry
swift crag
#

Space.Self would still only be correct for a camera pointing in the +Z direction, and your camera would also move faster in one axis than the other if your screen wasn't perfectly square

languid spire
#

I still see no reason whatsoever for ScreenToViewportPoint

swift crag
#

since moving right in the camera's own space moves you right in view space

swift crag
#

(this will only makes sense for an orthographic camera)

languid spire
#

Sorry, but the code is complete and utter nonsense

karmic kindle
#

I have a 3D game where the camera has "free movement within a box" (I've set limits) - I recently updated the camera script to used the keyboard to move forward, that code now works when I rotate the camera, but I'm having trouble adjusting the code for moving the camera via mouse click. Everything I've googled says that what I have should work, but it doesn't fit what I need.

Space.World = ignores rotation & Space.Self moves the camera on the Y axis too.

If one of you could go - "learn this" or "do this" that would be absolutely fantastic.

@wintry quarry Thank you. I'll look into that now.

karmic kindle
swift crag
#

This will give you a world-space vector that moves the camera left/right and up/down

languid spire
karmic kindle
languid spire
swift crag
#

you should stop and reason about why this works (and why the old code didn't work), though

karmic kindle
languid spire
karmic kindle
# swift crag you should stop and reason about **why** this works (and why the old code didn't...

It's concepts, I'm new to everything. I had code that worked and all I've changed is rotation, so my simplistic brain is struggling to find where I go to translate what I learned before, to what I need to know now. Forums and videos are too specific so it hasn't help me, then I come here for some humans to discuss and I'm met with arrogant people like SteveKingSmith.

I tried to reason long before I tried to ask for help

karmic kindle
swift crag
#

you want to write each line of code with purpose

karmic kindle
#

I understand that.

swift crag
#

you can use Debug.DrawRay to visualize a vector, which is useful for finding problems like this

#
Debug.DrawRay(Camera.main.transform.position, moveVector);
#

if moveVector is very short you might want to normalize it

#

and to see the line for more than one frame, you can do...

#
Debug.DrawRay(Camera.main.transform.position, moveVector.normalized, Color.red, 0.5f);
languid spire
weak grove
#

hello, i bring love and sprinkles lol

#

just learning about casting between int and doubles and floats

willow scroll
weak grove
#

im starting to remember my uni education on programming

languid spire
weak grove
#

yeah just a way of avoiding a compilation errror

#

nothing majjor lol

bright violet
#

Am I missing something? I get Object reference not set in the if statement for the distance calculation ```cs
void FixedUpdate()
{
//Scanning for each object in the _interactableMask that overlaps the Sphere
_numFound = Physics.OverlapSphereNonAlloc(_interactionPoint.position, _interactionPointRadius, _colliders, _interactableMask);

//if an Interactable object is found
if (_numFound > 0) { 
    //Find the closest collider
        Collider closestCollider = null;
    foreach (Collider collider in _colliders)
    {
        Debug.Log("collider in _colliders is: " + collider);
        if (closestCollider == null)
        {
            closestCollider = collider;
            Debug.Log("closestCollider is: " + closestCollider);
        }
        else
        {
            if ((_interactionPoint.transform.position - collider.transform.position).sqrMagnitude < (_interactionPoint.transform.position - closestCollider.transform.position).sqrMagnitude) //THIS LINE ERRORS
            {
                closestCollider = collider;
                Debug.Log("closestCollider is now set to: " + closestCollider);
            }

        }
    }
    //Store the closest colliders Interactable interface
    var _interactable = closestCollider.GetComponent<IInteractable>();
    Debug.Log(closestCollider);
    //Interact on input
    if (_interactable != null && playerInput.Player.Interact.ReadValue<float>() != 0)
    {
        _interactable.Interact(this);
    }

}

}

ivory bobcat
bright violet
#

it must be something dumb i'm just not getting it for some reason

karmic kindle
ivory bobcat
#

Post the error from the console

languid spire
#

@karmic kindle Look at this line of code

Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);

So what it does is calculate a Viewport point based on the difference between, I assume, 2 screen points.
in what way do you think this is a useful thing to do?

bright violet
ivory bobcat
#

What line is 46 of the Interactor script?

bright violet
#

the distance check if statement

astral falcon
karmic kindle
swift crag
#

"shortcuts" basically always cause problems

#

you never want something to work by coincidence

astral falcon
bright violet
karmic kindle
karmic kindle
languid spire
bright violet
slender nymph
slender nymph
#

oh you know what, you're just looping over the entire array regardless of how many objects were found by OverlapSphere

ivory bobcat
slender nymph
#

did you not read the documentation about how that method works?

ivory bobcat
#

You may want to iterate relative to the return value of num found rather than just evaluate every element

slender nymph
#

the better option is using a for loop to loop over the correct number of objects rather than just null checking everything. because old colliders could still be in the array and those shouldn't be checked either

bright violet
slender nymph
#

the method doesn't allocate anything. you allocated the array with a set size. the OverlapSphere method just populates the array with what it finds

#

and also returns the number of colliders found

ivory bobcat
bright violet
ivory bobcat
#

num found variable

languid spire
bright violet
astral falcon
slender nymph
astral falcon
bright violet
slender nymph
#

read the documentation

karmic kindle
bright violet
languid spire
swift crag
#

No matter how the camera is rotated, view space is going to range from [0,0] in the bottom left corner of the screen to [1,1] in the top right corner

#

by using ScreenToWorldPoint, you'll get world space positions

#

which will depend on the camera's rotation

#

however, note that this will not work correctly if you're using a perspective camera

#

you'll need to add a depth (the Z component of a screen space position) first

#

the depth you pick will affect how quickly the camera moves

#

if you pick a depth of 1 meter, moving the mouse will move the camera by the exact amount needed to keep an object 1 meter away under the cursor

#

So if the game world is exactly 10 meters away from the camera, a depth of 10 would be appropriate -- that'll make it feel like you're grabbing the game world and moving it around

karmic kindle
swift crag
#

consider using Debug.DrawRay to see how ScreenToWorldPoint behaves (both with and without changing the Z component of the screen space position)

astral falcon
#

Just a quick tip, move to the new input system one day 🙂

karmic kindle
#

I understand what ScreenToWorldPoint is doing, what I am struggling to understand is why does it apply in this situation?

As far as I understand, the mouse is a way for a player to interact with the screen. All I want to do is get a distance from them, then apply it to my camera view. So if they drag the mouse** "down" the screen, it will drag the camera "forward" - I don't see a need for any correlation between "ScreenTo#" ?

astral falcon
swift crag
#

I thought you just wanted to be able to drag it around...normally

#

so if you move the mouse down your screen, the camera moves up your screen

#

keeping the mouse in the same position in the world

#

you're talking about "forward" now

karmic kindle
#

I want my mouse to replicate what [WSAD] are doing but by mouse drag

swift crag
#

okay, and are WASD panning the camera up, left, down, and right, relative to your point of view?

karmic kindle
swift crag
#

This works if and only if the camera is pointing in the +Y or -Y directions

swift crag
#

oh, wait, that's got cam.transform.forward.x

#

i see

#

that is a bit weird

#

I would have expected you to do this

#
Vector3 moveDir = xInput * cam.transform.right + yInput * cam.transform.up;
swift crag
#

oh, you're doing this for every single key, separately

karmic kindle
swift crag
#

You want the camera to move in the X and Z directions

#

But the camera is not pointing straight down

#

It's angled

#

Is that correct?

karmic kindle
#

Yes

#

Then, when I rotate, it breaks the mouse movement

swift crag
#

okay, that explains a few things

#

and you're rotating it around the Y axis?

karmic kindle
#

Yeah

swift crag
#

not tilting it and not rolling it

karmic kindle
#

E.G if (Input.GetKey("e") )// || Input.mousePosition.x <= panBorderThickness) { transform.Rotate(Vector3.up * panSpeed * Time.deltaTime, Space.World); }

swift crag
#

okay, let's fix this up first; your camera is moving slower forwards and backwards than left and right

#
Vector3 forward = Vector3.ProjectOnPlane(cam.transform.forward, Vector3.up).normalized;
Vector3 right = Vector3.ProjectOnPlane(cam.transform.right, Vector3.up).normalized;
#

This will get rid of the Y component of these vectors.

#

it then normalizes them so that they have a length of 1 again

#
Vector3 moveVec = Input.GetAxis("Horizontal") * right + Input.GetAxis("Vertical") * forward;
moveVec = Vector3.ClampMagnitude(moveVec, 1);
transform.Translate(moveVec * panSpeed * Time.deltaTime, Space.World);
#

construct a movement vector, clamp its length to 1 (so that diagonal movement isn't faster), and then move with it

swift crag
#
Vector3 viewDelta = newViewPosition - oldViewPosition;
Vector3 moveVec = viewDelta.x * right + viewDelta.y * forward;
// the rest is the same, except that you don't use deltaTime
swift crag
karmic kindle
#

Thank you everyone, there's a lot of information to digest so hopefully I can absorb it all hehe, but I do really appreciate the extra lessons and advice! 🖖

#

I'd love a beer but I'm going to take a break, maybe I'll come back to shout it's working and bug you that way 😛

swift crag
#

getting to know the Vector3 methods (along with Quaternion) is very important

#

any time I see someone pulling out individual components of a world-space vector, there's probably an issue

stuck palm
#

i changed my canvas from an overlay space to a screen space thing, and now my raycast for selecting characters is messed up. how can i sort this out??

if (_playerInputController != null && !_playerInputController.characterSelected)
        {
            _transform.anchoredPosition += _playerInputController.markerMove * (speed * Time.deltaTime);
            _transform.anchoredPosition = new Vector2(
                Mathf.Clamp(_transform.anchoredPosition.x, -896, 896),
                Mathf.Clamp(_transform.anchoredPosition.y, -485, 485)
            );
        }
        PointerEventData eventData = new PointerEventData(EventSystem.current)
        {
            position = _transform.anchoredPosition
        };
        var results = new List<RaycastResult>();
        EventSystem.current.RaycastAll(eventData, results);
        bool foundCharacter = false;
        foreach (RaycastResult result in results)
        {
            if (result.gameObject.CompareTag("CharacterSelect"))
            {
                if (result.gameObject.TryGetComponent(out cb))
                {
                    _playerInputController.selectedCharacter = cb._characterInfo;
                    if (!characterHovered)
                    {
                        source.PlayOneShot(hover);
                        characterHovered = true;
                    }
                    foundCharacter = true; 
                    break;
                }
            }
        }
frank zodiac
#

is LoadSceneAsync is the same as LoadScene? What's the difference?

slender nymph
#

it loads asynchronously

frank zodiac
summer stump
#

Usually wiki is too wordy, but this one is good imo

frank zodiac
#

thanks!

stuck palm
#
if (_playerInputController.characterSelected)
            {
                _playerInputController.characterSelected = false;
                _playerInputController.selectedCharacter = null;
                _playerInputController.colorNum = 0;
                print("Removed character!");
                return;
            }

            if (!_playerInputController.ready && !_playerInputController.characterSelected)
            {
                _playerInputController.pi.user.UnpairDevicesAndRemoveUser();
                Destroy(_playerInputController.gameObject);
                markerGraphic.SetActive(false);
                if (TryCancel != null) TryCancel(id, _playerInputController);
                print("Deleted player!");
                source.PlayOneShot(hover);
            }

why does it execute both even though there is a return statement?

slender nymph
#

those are probably happening in separate frames or this code is being called more than once in the same frame

stuck palm
obtuse cove
#

Sorry for the trouble, I have a problem with this script, it doesn't give me errors but when I start the game some fireballs rumble very quickly on the ground and if the character touches them they move but they don't disappear anyway

stuck palm
#

no idea why, though. this check is meant to happen when the player clicks a button. even stranger is this exact system works as intended in another mode.

slender nymph
#

use the debugger and set some break points to determine why that code is being executed more than once

willow scroll
eternal falconBOT
crisp knoll
#

!code

eternal falconBOT
swift crag
#

the method returns immediately

terse plume
#

If I add 2 audio listeners or event systems i get a warning that i should not do that...
Could I make only one of each and keep them in a "Dont destroy on load"? 🤔
Is there any adverse effect with doing that?

astral falcon
#

If you add a camera, remove the listener. And for sure always have one eventsystem, because all the API is going into that eventsystem and two will confuse your code on which to use

swift crag
#

Audio listeners are generally attached to a camera

#

so it's less reasonable to do that (you presumably have different cameras in your main menu and your actual game)

polar acorn
swift crag
#

I have my EventSystem on a "main menu" prefab that gets instantiated the moment the game starts

polar acorn
swift crag
#

nothing else has an event system

#

(i fetch the main menu from Resources)

void thicket
#

Unity could’ve done something different than making user to ensure single instance

#

But well

swift crag
#

(Safe is there so that I can avoid creating more copies of the prefab as the game quits)

frank zodiac
#

how do i limit the length of a raycast?

void thicket
slender nymph
frank zodiac
frank zodiac
#

nevermind i found the parameter

void thicket
#

lol

slender nymph
signal spruce
#

If i have a heart container with collider 2D (Set to trigger), animator and the script, and when i enter the trigger i want him to dissapear and make a sound, is there any way to play the sound on the heart container with his audio source but without having to deactivate each component 1 by 1?

slender nymph
#

don't make the audio source a child of the object being deactivated

boreal hare
#

Hello Is there a paint system in unity like a drawing app and save drawing as .png format

wintry quarry
#

Use AudioSource.PlayClipAtPoint

signal spruce
wintry quarry
#

They wrote "don't"

slender nymph
#

the first word is literally "don't"

boreal hare
wintry quarry
#

Yes you would write the code

signal spruce
#

so what should i do with the audio to work? like i dont have childs its just a gameobject

#

with each component on it

boreal hare
#

No!!! I'll find a tutorial

slender nymph
#

i personally have an AudioManager class that pools a bunch of audio sources and works very similarly to PlayClipAtPoint, just using the pooled sources

signal spruce
frank zodiac
#

is there a definitive way to make a raycast? i saw a lot of youtube tutorials but they say different things

#

i want to make a raycast and check if its touching a layer

slender nymph
#

there's also documentation you can read

signal spruce
#

I think that method is perfect

#

I guess if the object is moving and the sound is long I have to do the other thing 100%

slender nymph
#

just note that using that method frequently is going to generate quite a bit of garbage since it creates and destroys audio sources

signal spruce
slender nymph
#

the garbage

signal spruce
#

like residual memory?

slender nymph
#

as in the memory being allocated then needing to be cleaned up frequently

signal spruce
#

that affects to performance I guess

slender nymph
#

a lot of garbage needing to be collected can cause hitching whenever the GC runs

polar acorn
#

"Garbage" is a term in programming referring to allocated memory that is no longer referenced anywhere. Most modern programming languages will free that memory for you so you don't need to worry about allocation, but that still does take time, and clearing garbage very often can lead to noticeable framerate drops

signal spruce
#

the thing is if the object is moving and the sound is long the clipatPoint wouldnt be a good idea cause it doesnt follow the player, or maybe you can attach as a child while the audiosource is alive?

polar acorn
slender nymph
#

this solution was for when the object is being deactivated/destroyed and you want a sound to play, not for long running sounds that must follow an object

dusty silo
#

Why does ```cs
for (CircleCollider2D in Physics2D.OverlapCircleAll(pos, .2f)){

    }
Throw a syntax error?
void thicket
wintry quarry
#

and

#

other reasons

#

there are several problems yes

slender nymph
#

also ideally you should use OverlapCircleNonAlloc and a regular for loop

wintry quarry
#

Are you a Python programmer by chance

dusty silo
#

No

wintry quarry
#

foreach uses in. for does not

dusty silo
#

Ah. I forgot about foreach. Thanks

wintry quarry
#

But you still need a name for your variable

void thicket
#

And you'll get Collider2D

lime pewter
#

Anyone know how to align tilemap position with gameobject position? I am currently trying to create a liquid system using cellular automata, which requires me to check for a tilemap tile beneath it to decide whether it should fall or not, and currently they are off-centered so when I convert my transform.position of my liquid gameobject to a vector3int required for the "HasTile" function of Unity tilemaps, it (unless very conveniently placed) will always think there is not a tile below. Any ideas would be amazing!

lime pewter
dusty silo
slender nymph
#

you will need to type check the colliders inside the loop then

#

there's no way to filter for a specific collider type until then

void thicket
signal spruce
#

Is there anyway to edit a tilemap without getting lag? I have a big map with a lot of tiles and its really laggy and a lot of timesI get the loading pop up, but if i edit in prefab mode even tho is not that laggy each time i do something it also gets the pop up but with the import text

void thicket
#

Giving foreach variable specific type gonna cast it and throw if type mismatches

rich adder
signal spruce
rich adder
wintry quarry
#

use the built in tools

lime pewter
#

Yeah, I assumed there was something like that I was missing. Appreciate it!

warm thorn
#

Hello there folks! Anybody perhaps know how to hide GameObject content in scene hierarchy and whats important - still allow selecting it in scene?

So far I tried:

  1. Using this callback: https://docs.unity3d.com/ScriptReference/EditorApplication-hierarchyWindowItemOnGUI.html, sadly I got no idea how to use GUI nor hide hierarchy items, so I could not achieve anything useful :(
  2. Using hide flags: https://docs.unity3d.com/ScriptReference/Object-hideFlags.html, closest to that what I want to do, but still not enough. HideFlags.HideInHierarchy do indeed hide it in hierarchy, but also dirty scene and prevent selection, second flaw can be avoided, by putting objects into GameObject and setting hideflag only for that gameobject, but that means all prefabs needs to be modified which is pain for me :(

Sooo, second solution somewhat works with annoying flaws so far, but first one would be perfect, sadly I got no idea how to use GUI there, I would appreciate any help, thx

void seal
#

I'm trying to just rename a script and my player object can't make any reference to it if I do. It tells me to alter the prefab but it's greyed out?

#

Ok well now that script just disappeared on it's own that's awesome.

polar acorn
void seal
#

I did that too.

#

man

grave frost
#

for the future

void seal
#

It's back I guess? But still gives this error.

astral falcon
void seal
#

Neither of those help this specific circumstance.

slender nymph
#

why wouldn't that help? that goes over everything you need to check to ensure your component is loaded correctly

grave frost
#

you gotta look at your console my man. follow the links there. You can see it says "console errors" as one of the options. Click that.

void seal
#

You're giving me advice and I'm saying I've already done both to no avail.

wintry quarry
#

show your console

summer stump
wintry quarry
#

show your code

summer stump
polar acorn
eternal falconBOT
signal spruce
final kestrel
#
public override void OnInteract()
    {
            inventoryManager.AddItem(item);
            Debug.Log($"Item {item} added");
            gameObject.transform.localPosition = handPosition.transform.localPosition;
            gameObject.transform.SetParent(handPosition.transform,false);
            isInHand = true;
    }

It parents the child object with offset

#

handPosition is just an empty

#

I want it to be exactly where my empty is at.

#

When I run this code its like my object stays a bit further from the handPosition

summer stump
#

Oh, too slow. You already went there haha

slender nymph
#

you also never need to use gameObject.transform, every component already has a reference to its transform through its own transform property

final kestrel
slender nymph
final kestrel
#

Ah okay, makes sense. Thanks a lot.

void seal
#

ngl that was a lot of pressure with those ats

final kestrel
#

So uhh. I parent the object when I take it in my hand. How can I put it back on the ground without physics. Like it will just unparent and be on the ground.

#

Should I unparent and parent to the ground?

#

It just stays like this when I try to drop it 😄

swift crag
#

parenting it to the ground doesn't make it move

#

it's just going to follow the ground around now

#

you can use a raycast to find a spot on the ground to place it

frank zodiac
#
public void OnJump(InputAction.CallbackContext context)
{
    if (context.performed && isGrounded)
    {
        Vector3 newVelocity = new Vector3(rigidbody.linearVelocity.x, jumpForce, rigidbody.linearVelocity.z);

        rigidbody.linearVelocity = newVelocity;
        animator.SetBool("isJumping", true);
    }
}

private void Update()
{
    if (Physics.Raycast(transform.position, -transform.up, 0.5f, groundLayer))
    {
        isGrounded = true;
        animator.SetBool("isJumping", false);
    }
    else
    {
        isGrounded = false;
    }
}

is there anything wrong with my code?

polar acorn
frank zodiac
#

the jumping works though

final kestrel
polar acorn
swift crag
frank zodiac
final kestrel
polar acorn
swift crag
frank zodiac
final kestrel
swift crag
#

move the box there, presumably

#

since you just found a spot on the ground

#

Note that this would put the box halfway into the ground

final kestrel
#

Yeah I need to offset it a bit then?

swift crag
#

can the box be rotated?

#

and if so, should it stay rotated when you drop it?

pulsar elk
#

can anyone send me an easy script to pause/resume my game? like by pressing p the game just freezes and by pressing again it unfreezes? its first person template btw

final kestrel
#

It should reset its rotation when dropped.

swift crag
#

okay, so you can just set its rotation back to Quaternion.identity, then raise the point you find on the ground by half of the box's height

final kestrel
#

Goddamn I have to do this with all my equippable items then?

swift crag
#

you can automate it a bit

final kestrel
#

I guess I can make a method and do it inside.

swift crag
#
transform.rotation = Quaternion.identity;
Physics.SyncTransforms();
Vector3 offset = collider.bounds.y / 2 * Vector3.up;
swift crag
#

something like that

frank zodiac
swift crag
#

the SyncTransforms is needed so that the physics system learns about the new rotation

frank zodiac
polar acorn
final kestrel
polar acorn
#

I said to check the Y velocity as part of your grounded condition

swift crag
#

You could also use a renderer to figure out some bounds automatically, I guess

polar acorn
#

So that you're considered grounded when the raycast hits and your Y velocity is 0 or less

swift crag
#

But it'd be nice to just define the size of the object once (with a box collider)

final kestrel
#

It just feels like I'm doing everything wrong and not reusable haha.

frank zodiac
#

like this?

frank zodiac
#

maybe i could decrease animation speed

#

or decrease jumpingforce

grave frost
frank zodiac
#

youre a godsend

dense root
#

How do I make sure my player is facing forward? I tried the simple way of changing the sprite to them in the forwards idle position but they reset back to idle downwards

Here's my player controller script code for reference: https://gdl.space/mokuduzozu.cs

final kestrel
# swift crag This just uses the a collider to figure out the size of the object.

I did this now i cannot event drop it

bool canDrop =Physics.Raycast(transform.position, Vector3.down,out RaycastHit hit, 10f, groundLayerMask);
        if (isInHand && Input.GetKeyDown(KeyCode.Q) && canDrop)
        {
            item = inventoryManager.GetSelectedItem(true);
            transform.SetParent(null);
            transform.position = hit.transform.position;
            transform.rotation =Quaternion.identity;
            inventoryManager.DropItem(item);
        }
dense root
final kestrel
shell apex
#

Heya! I'm trying to set up vscode with unity. I installed the plugin and got it set as the editor, but intellisense isn't working, so autocomplete and code insight features aren't working. I don't know what I'm doing wrong, any help is apprecieted

slender nymph
#

!vscode

eternal falconBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

slender nymph
#

follow all of the instructions there

shell apex
#

I did all that already

slender nymph
#

then regenerate project files and restart vs code

#

also if you've only just installed the c# extension, make sure to restart your PC

queen adder
#

so i want to basically move an object directly onto my mouse if that makes any sense i want it to move like its being set to the position of my mouse except its using a rigidbody heres my code and how it works

slender nymph
#

make the rigidbody kinematic for the duration you are moving it with the mouse so it doesn't do that

#

then you can just set the position of the rigidbody

queen adder
#

i have gravity disabled rn

#

hold on

shell apex
final kestrel
#
 void Update()
    {
        bool canDrop =Physics.Raycast(transform.position, Vector3.down,out RaycastHit hit, 10f);
        if (isInHand && Input.GetKeyDown(KeyCode.Q) && canDrop)
        {
            item = inventoryManager.GetSelectedItem(true);
            transform.SetParent(null);
            transform.position = hit.point;
            transform.rotation =Quaternion.identity;
            inventoryManager.DropItem(item);
        }
       
    }

So this drops the object(at hit point) it goes into the ground though. I could not manage to offset it. How do?

swift crag
#

by adding Vector3.up (times the appropriate value) to the position

slender nymph
# shell apex It still doesn't work

if you cannot get vs code to work by following the guide, then consider switching to a real IDE like visual studio which is far less likely to break

shell apex
#

I can't use visual studio on linux

queen adder
shell apex
queen adder
#

i want it to build momentum horizontally as well while being held

slender nymph
final kestrel
swift crag
#

Yes, you'd be calculating a new position

dense root
#

Any clues on how to set the player's positon to up when inside? Here's what I've attempted so far

/*
 * if Player is inside
 * Set direction to up
 */

if (isInside)
{
    transform.position = Vector2.up;
}```
queen adder
#

is there away i can get a similar effect of setting the position to where the mouse is just by using a rigidbodys force and velocity

grave frost
final kestrel
grave frost
final kestrel
#

Ah okay I'll try

#
 void Update()
    {
        bool canDrop =Physics.Raycast(transform.position, Vector3.down,out RaycastHit hit, 10f);
        if (isInHand && Input.GetKeyDown(KeyCode.Q) && canDrop)
        {
            item = inventoryManager.GetSelectedItem(true);
            transform.SetParent(null);
            transform.position = new Vector3(hit.point.x, hit.point.y  * 2f, hit.point.z);
            // transform.position = hit.point;
            transform.rotation =Quaternion.identity;
            inventoryManager.DropItem(item);
        }
       
    }

This also works but I'll do it your way I just tried the number.

swift crag
#

This would double the world Y position

#

which would be correct at...one Y-level

final kestrel
#

ah by one y level you mean if any ground is higher or lower I'd have to come back and adjust it accordingly?

swift crag
#

yes, since your'e just doubling the Y position of the object

#

in world space, so it depends on where the ground is positioned

#

You can just give each item a "size" field that tells it how to position itself

#

You could even store a Quaternion that represents how it should be rotated when on the ground

grave frost
final kestrel
#

stored the collider at start.

final kestrel
swift crag
#

you're using the current position of the object..

final kestrel
#

oh yes there is nothing about hit.point

swift crag
#

you need to stop and think about what these numbers actually mean

#

otherwise you'll just be banging random variables together

#

you should create a few variables instead of doing everything in one big one-liner

#
Vector3 point = hit.point;
point += Vector3.up;
transform.position = point;
#

for example

final kestrel
swift crag
#

right!

#

you'd want to do something more clever than that

#

liike what Heroshrine suggested

final kestrel
#

transform.position = new Vector3(hit.point.x, hit.point.y +_collider.bounds.extents.y/2 , hit.point.z); Wat about this!

swift crag
#

break it up!

#

but it looks reasonable enough

#

one concern: your collider will still have the old rotation

swift crag
#

Imagine you're putting a stick on the ground, but it was rotated vertically in your hand

#

The bounds will be huge in the Y axis

final kestrel
#

ah yes I'm doing that as you said. Wait here is the full thing.

 void Update()
    {
        bool canDrop =Physics.Raycast(transform.position, Vector3.down,out RaycastHit hit, 10f);
        if (isInHand && Input.GetKeyDown(KeyCode.Q) && canDrop)
        {
            item = inventoryManager.GetSelectedItem(true);
            transform.SetParent(null);
            // transform.position = new Vector3(transform.position.x, transform.position.y + _collider.bounds.extents.y/2,transform.position.z);
            transform.position = new Vector3(hit.point.x, hit.point.y +_collider.bounds.extents.y/2 , hit.point.z);
            // transform.position = hit.point;
            transform.rotation =Quaternion.identity;
            inventoryManager.DropItem(item);
        }
       
    }
willow scroll
# obtuse cove Sorry for the trouble, I have a problem with this script, it doesn't give me err...

First of all, you have a condition for your prefabs to spawn if the elapsedTime, increased by Time.deltaTime in the Update method, is smaller than the random value between the minimum and maximum spawn time. This is going to spawn quite a lot of fireballs at the beginning of the game.

elapsedTime += Time.deltaTime;

if (elapsedTime >= Random.Range(minSpawnTime, maxSpawnTime))

This is also not a great way to do it, since the number of spawned fireballs is going to increase according to the user's fps

final kestrel
#

How the hell am I supposed to use this logic on every item object T_T I gotta think now.,

#

Thanks for all the help it works perfecto now!

swift crag
#

you can either inherit from it (to create more specific kinds of items) or just use it along with other components

#

a tool could have an Item component (that handles picking up and dropping it) and a Tool component (that lets you do something with it)

final kestrel
#

Hm I have an Item SO

#

I must do some thinking...

shell apex
swift crag
#

I have v1.6.8, which works just fine

#

you have to follow every step on the page; you can't skip over or re-interpret anything on it

latent sedge
#

if (Input.GetMouseButtonDown(0))
{}

What is the condition for this method? What is the 0 doing in this circumstance?

swift crag
#

notably, you need to have:

  • the correct packages installed in Unity
  • the correct code editor selected in Unity
  • the correct extension installed in VSCode
shell apex
swift crag
#

the last comment suggests the pre-release version fixes this

shell apex
#

Oh neat, I didn't see that

swift crag
#

it was installed by the .NET Install Tool extension

dense root
#

Anyone ever spend an hour working in a script just to realize you're in the wrong script? 😂

vagrant pendant
#

can someone help me with understanding how I can implement my player's head's face always being where the camera is looking, but allowing the body to rotate independently with tank controls? (will start a thread w/ a diagram)

grave frost
# swift crag liike what Heroshrine suggested

What I suggested though only works if the collider is the size of the object. In reality you also probably want some “offset” vector serialized in the inspector to add to it so you can fine tune it. So basically, both of what we said lol.

#

@final kestrel

swift crag
#

yeah, I'd just store a rotation and oposition offset

final kestrel
#

But thanks a lot for the help. I made it work!

final kestrel
slender nymph
grave frost
#

I know this is a coding channel, you should do what boxfriend said. However, I dont think you’d be able to do it with animations since im pretty sure the only thing it can export as that unity can read is a obj file. So you’d need to re-create the animations in unity.

obtuse cove
polar acorn
#

Show code

rocky canyon
#

telling you where ur question belongs is helpful imo.. lol
if im ever visiting some foreign country i'd rather people tell me directions than point out that they aren't a map

#

that said, I thought FBX's could include animation

slender nymph
#

turns out they crossposted from the correct channel to here anyway. they are probably just mad that nobody spelled out the answer for them or that they never even got a response in the correct channel because they barely put any effort into their question

rocky canyon
#

holy heck, FBX means Filmbox 🤯

sterile radish
#

i want to make it so that a ball in my game makes a counter go up by 1 everytime it bounces and i did this by checking whenever it collides with something. however when it has stopped bouncing and is laying still on the ground, it just continues to increase the counter because it's still technically colliding with something. how do i fix this?
https://hatebin.com/lzdkwsqurd

slender nymph
#

you've pasted the class in there twice, but OnCollisionEnter2D is only called when the collision is first entered, it is not called continuously until it has ended so whatever is increasing the score continuously is happening elsewhere

rocky canyon
#

if its helpful u can log the collision w/ debug class and check the console.. see whats causing collisions
my character has a landed mechanic.. soo when I jump and i lose contact with the ground i change my bool inTheAir
then only if thats true.. and i collide with the ground it calls a function.. this sets the air bool to false.. so the
function doesn't count any more of hte collisions unless i jump and leave the ground again

#

but OnEnter is fast and simple

sterile radish
rocky canyon
#

no problem 🍀 good luck

rocky gale
#

What is up

rich adder
#

a direction

rocky gale
#

Y axis

polar acorn
rocky gale
#

I have math class rn 😢

rocky canyon
#

Vector3(0,1,0);

rocky gale
#

I actually have to go goodbye

rocky canyon
#

<looks around> okiedokie

sick ether
#

im seeing something abnormal which the docs say shouldnt be. Im registering C# events in OnEnable and OnDisable but getting null reference exceptions. if i have one such registering object, it works as expected. if i have two or more, then any gameobject after the first gets null reference exceptions. however, if i move the de/registration to Start and OnDestroy, everything works fine. I have verified my script excecution order is at defaults, etc. anyone else seen this?

slender nymph
#

is the NRE happening when you invoke the event, or when you try and subscribe to the event

sick ether
#

it's getting thrown in OnEnable upon trying to reg. but, again, only for GOs beyond the first one.

slender nymph
#

show relevant code, how you subscribe as well as the object the event is on

sick ether
#

the event is being fired by a Singleton.

slender nymph
#

well that validates my assumption that you are likely destroying the object you are referencing in those objects that subscribe to the event. you still need to actually show relevant code so that we can confirm what is actually happening

sick ether
#
        {
            // subscribe to the event
            TimeManagerScript.Instance.TickWithID += this.tickedUpdate;
        }```
#

the reg'ing GOs have that. OnDisable is same but -=

slender nymph
#

now show the singleton like i already asked you to

sick ether
#

sry. misiunderstood. no need to be jerk

#

TickWithID?.Invoke(new TickEventArgs(this.ticks));

#

like i said, it's straightforward and weird.

slender nymph
#

not being a jerk, you're just making assumptions. but now i'm not going to help you, good luck

sick ether
#

cool. you too

slender nymph
#

also FYI, i didn't want just the line where you invoke the event. the entire class would have been helpful

#

hence why i said "the object the event is on" and not just "only the line where you invoke the event"

sick ether
#

ive moved on. you should too

slender nymph
#

oh my bad, here i was thinking that helpful advice might actually help you get the help you are seeking in the future. if you don't want to get help from anybody though, that's fine too

sick ether
#

fair, i retract my last.

#

ill figure it out. ty for offering to help

#

(but there is zero way that saying, "as i already asked" isn't something less than polite)

summer stump
#

It is a polite reminder imo

sick ether
#

fair. it doesnt come off that way to me. maybe it's subjective.

#

or we just have different expectations. all good.

ivory bobcat
#

Some common members of this server ends remarks with "..." - not implying dissatisfaction but etc (the rest)
Don't read into it too much. It's just text unless they outright insult you.

topaz fractal
#

when i use 2 input directions, my movement speed increases, how do i fix this?

polar acorn
rocky canyon
#

RandomUnityInvader(); must be out. just wanted to chime in for him lol

dense root
#

Is this the right way to get a button onclick and offclick? It seems to not work as intended

public void OnPointerDown(PointerEventUnit pointerEvent)
{
    buttonPressed = true;
    mText.text = "a";
}

public void OnPointerUp(PointerEventUnit pointerEvent)
{
    buttonPressed = false;
    mText.text = "Hint";
}
polar acorn
dense root
rocky canyon
#
using UnityEngine;
using UnityEngine.EventSystems;

public class ButtonClicker : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.Log("button pressed");
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("button released");
    }
}
``` you'll need an EventSystem and a GraphicRaycaster component w/ this setup @dense root
lime pewter
#
private Collider2D GetLiquid(Vector3 position, Vector2 direction)
    {
        RaycastHit2D hit = Physics2D.Raycast(position, direction, 0.5f, layerMask: 4);

        Debug.DrawRay(position, direction, Color.red, 5f);

        return hit.collider;
    }

Hey! I am currently creating a function that is supposed to simply detect whether there is a liquid in any cardinal direction for use in a liquid simulation script, however it is always returning null even when there is a very clear ray going through the collider when using "Debug.DrawRay", if anyone has any ideas as to why this may be any help would be amazing! it is currently being used in an if statement as so:

GetLiquid(transform.position, Vector2.right) == null
#

They all have "Box Collider 2D" components with the proper sizing as-well.

slender nymph
#

your layer mask will only detect things on layer index 2, which also happens to be the Ignore Raycast layer

rocky canyon
#

🤯

#

what a twist

lime pewter
#

oh! Haha, that's probably not a great thing. Is layerMask: 4 not the layer labelled 4?

rocky canyon
#

nope

slender nymph
#

no, read the link i sent

rocky canyon
#

ur in for a treat

#

could always define a layermask and populate it in the inspector

lime pewter
#

oh fantastic, I'll just define it haha.

rocky canyon
#

thats what i do.. cuz i suck at bitshifting and watnot

lime pewter
#

That seems a little unintuitive in my inspector but I appreciate the help!

#

LayerMask.GetMask("Water"); would return the "Water" layer's bitmask I assume?

slender nymph
#

you are trying to use a layer index, but layer masks are bitmasks

rocky canyon
#
int layer4Bitmask = 1 << 4;
Debug.Log(layer4Bitmask);```
#

something like that lol
edit: actually idk, so why i use layermasks

lime pewter
#

okay, perfect! I appreciate the explanation, I suppose that makes sense. There are a lot of different "masks" in unity that all have wildly different usecases I see haha.

rocky canyon
#

yea check out this link when u got time

lime pewter
#

Yeah, I'll just be using layermasks as they seem a little easier to read lol.

lime pewter
rocky canyon
#

nah, probably later on you'll find a need for em

lime pewter
#

I'm just mocking up a simple cellular automata liquid script and I was wondering why it wasn't watering haha

lime pewter
rocky canyon
#

so layer 4 is 16
you can bitshift 4 spaces 1 being 0001, so 4 spaces 1 << 4 is 10000 which is binary for 16

#

im talkin out my arse tho.. lol cuz i get amazed anytime someone else explains it..

#

esp when they explain it like its 2nd nature

lime pewter
#

haha, I'll probably look into it. It sounds pretty interesting but I'm too tired to not take the easy route of LayerMask.GetMask with a string ahah

#

already working on a decently complicated concept for water simulation right now, anything more and I might just cry lol.

rocky canyon
#

theres a raycast overload that takes in a layermask

#

wouldnt even need to convert it to a string or anything

#
Physics2D.Raycast(transform.position, Vector2.right, Mathf.Infinity, layerMask);```
#

"Ray hit something on one of the specified layer(s)."

lime pewter
rocky canyon
#

could just chose Water in the layermask.. and just use a layermask but i guess that works too ^

#
                if(Physics.Raycast(transform.position,targetDir,out tempHit,rayDistance,layers))
                {
                    hit = tempHit.collider.gameObject;
                    success = true;
                }``` one of my raycasts
lime pewter
final kestrel
#

How can I make the code blocks with color?

rocky canyon
#

hardcoding 😅 👻

#

spooky

#

your code block

#

three backticks the language -> enter to drop down a line.. -> paste ur code

#

then three more backticks

final kestrel
#

oh so cs makes them with color?

lime pewter
# rocky canyon hardcoding 😅 👻

yeah for now, the final implementation will almost definitely not be but inspector references break/release a ton if you mess with them wrong. I usually just hardcode and fix later ahah.

lime pewter
rocky canyon
#

cs makes C# code colored.. syntax highlighting

#
Theres many different languages it can highlight tho
lime pewter
#

there are a lot of usable languages which will color it.

#

You can use markup which allows you to directly color text I believe.

final kestrel
#

ah nice thanks a lot.

rocky canyon
#

discord doesn't allow markup it supports markdown tho

lime pewter
rocky canyon
#

Markdown

  • is
  • pretty
    • awesome tho
lime pewter
#

true

#

default dashes used in a list automatically convert to markdown I believe

  • test
  • test
#

yeah

rocky canyon
#

oh i found a bitshifting calculator.. thats cool

#

i bet i could write a function that takes in a layer number and returns the bitshifted value

#

would make me finally use em a bit more often lol

lime pewter
#

haha, maybe!

rocky canyon
#

for single layers its easy

slender nymph
rocky canyon
#

its multiple layers where i get screwd up

#

oh damn, see boxfriend already did it before i could finish thinking bout it haha

#

ya, i think i finally comfortable with single layers

#

just bit shift 1 by the number

slender nymph
#

doing multiple is just as easy.

public int LayersToMask(params int[] layers)
{
  var layerMask = 0;
  foreach(var layer in layers)
    layerMask |= 1 << layer;
  return layerMask;
}
rocky canyon
#

ohhhhhh i think i just had a rev-e-lation..
int combinedMask = layer1 | layer2 | layer3;

rocky gale
#

Revolution 😂

rocky canyon
#

savvy

#

rev-uh-lation rev·e·la·tion*

rocky canyon
lime pewter
#

also are you able to set a custom fixedUpdate rate?

rocky canyon
#

yessir

lime pewter
#

like 5 updates per second rather

rocky canyon
#

in the Time section

#

of Preferences or Project settings.. cant remember which one

#

or thru code

lime pewter
#

is there a custom FixedUpdate that allows you to define the updates/s

#

directly in code that is

rocky canyon
#

project settings it was

rocky gale
#

Wish

#

Woah

rocky canyon
#
 Time.fixedDeltaTime = 0.02f;```
rocky gale
#

It’s always that?

lime pewter
#

Alright, I'll look into it. Thanks!

rocky canyon
#

1f / desiredFPS; if u want to use ur desired frames per second instead

rocky canyon
#

50FPS stock

rocky gale
#

What’s difference between normal time delatime

rocky canyon
#

deltaTime is the time between frames.. depends on ur frame-rate
fixedDeltaTime is the physics step, and is locked to a constant value

rocky gale
#

Oh

rocky canyon
#

deltaTime is the Update()
and fixedDelta is the FixedUpdate()

rocky gale
#

I see

rocky canyon
#

constant fixed step = reliable physics

lofty sequoia
#

AddComponent creates a new instance when adding to an existing gameobject, right?

#

I don't have to call new before, correct?

slender nymph
#

you should never call the constructor for a component

dense root
#

I have this odd behavior where my text field is being changed yet the only time I call CorrectResponse is shown in this field.

    public InputField inputfield;
    [SerializeField] BattleManager battlemanager;
    [SerializeField] Text correctResponse;

    private void Start()
    { 
    }
    private void Update()
    {
        string inputText = inputfield.text; 

        if (inputText == "a")
        {
            //correctResponse.text = "Correct!";
        }

        //if (battlemanager.inBattle == true)
        //{
        //    inputfield.Select();
        //}
    }
wintry quarry
#

Did you save your code

dense root
#

Yup I did

#

I guess a better question is how do I diagnose what is calling my CorrectResponse game object? Since this script is obviously not the offender

rocky canyon
#

well if u disable or remove the component u should get a null error from the script trying to call it

dense root
#

Deleted the component but it's not throwing an error, very strange

rocky canyon
#

lol, must be that script then

rocky canyon
#

phantom code running i think

dense root
#

The intended behavior is for the text to appear within the box, yet somehow I coded it so that the Correct Response text displays the text being inputted

void thicket
#

Is your text input component referencing that correct response text?

slender nymph
#

show the input field component

void thicket
#

Yeah the inspector of it

rocky canyon
#

possibly some mixed up variables

#

oh that was the entire script

dense root
slender nymph
#

this is not the input field

void thicket
dense root
rocky canyon
#

it doesn't even have a text component assigned to it

void thicket
#

Why the text component none?

dense root
#

I think when I was tinkering I put a value there then removed it

#

Anyways it works now that I assigned the text component

rocky canyon
#

👍

dense root
#

Does Unity automatically go to a text component if none is found?

#

Because I thought in theory it should just do nothing with it

void thicket
#

I think it shouldn't

#

So that's weird

rocky canyon
#

heres another tip for ya, i used a text input field a while back for inputting a password.. and i could not get the fields to match.. even when they did..
turns out that there was an extra character that i couldnt see
password was the text i was looking for but
password was the text that it kept comparing

#

so might be something u run into. but it was long long time ago.. so may be a non-issue now

rocky canyon
dense root
#

Remove the Text variable and test again?

rocky canyon
#

text mesh pro input doesn't do it

void thicket
#

Sure you could do that for sanity check

rocky canyon
#

text mesh pro is like 'nah bro, u aint that lucky'

dense root
#

Well I deleted all the previous stuff but I can try it again if I am able to recreate it and then report back.

rocky canyon
#

👍 recreating a bug/issue is sometimes harder when ur trying lmao

dense root
#

lol

void thicket
#

Might be just gone like Heisenbug

shell apex
#

Is there any prior art for using a cylinder for a character controller's collision

#

I'm trying to do stuff with 3d platforming and using a capsule doesn't make sense and a box sucks for rotations

frosty hound
#

CCs don't use cylinders since they're not mathematically friendly for calculating physics/overlaps.

teal viper
summer stump
#

Probably edges. I was about to ask the same thing haha

shell apex
summer stump
# shell apex Falling off of edges

Just do a cast downwards and don't apply gravity is on the ground. A wider cast like circle, or multiple rays (front, back, and maybe middle)

teal viper
#

Maybe use a different method for ground checking then

rocky canyon
#

capsule is the best fitted collider

shell apex
#

I'm currently trying to implement a collide and slide algorithm for it using a kinematic body instead of a primitive, but it phases through surfaces when not moving across the surface's normal

#

This is my code for it

summer stump
shell apex
#

No I am not

summer stump
shell apex
#

My bad

slender nymph
#

what type of collider are you currently using on it?

shell apex
#

A cylinder

slender nymph
#

wdym a cylinder? there is no cylinder collider unless you are using Unity.Physics which is for dots

rocky canyon
#

hehe facts

shell apex
#

body is a RigidBody with a cylinder mesh

slender nymph
#

i asked about its collider

rocky canyon
#

the cylinder mesh uses a capsule collider

shell apex
slender nymph
#

so it's got a convex mesh collider. that is fine then

wheat rune
#

At first intellisense for the input system worked, but it didn't work in unity because i forgot to restart the editor, so I restarted unity & vs, but now intellisense doesn't work in vs and the input system does work in unity

slender nymph
#

regenerate project files and restart visual studio

wheat rune
#

thanks

sterile radish
#

how do you change the bounciness of a physics material 2D through script?

wheat rune
slender nymph
#

it doesn't do anything visually, but it will re-create the csproj files so that when you restart visual studio it uses the newly created ones which generally fixes issues with types and namespaces not being recognized in visual studio (if there isn't supposed to be an issue with it)

#

so if that does not work, then either you are using asmdefs in your project and need to reference the input system's assembly in your asmdef or you might need to regenerate your project's library

#

oh or you just aren't generating enough csproj files

#

although I will say i've not had issues with the input system namespace and i have 0 options selected for the csproj files

wheat rune
#

I've restarted vs and deleted library entirely

slender nymph
#

are you using asmdefs?

wheat rune
#

no, I'd have to look it up

#

not that I know of*

slender nymph
#

you would be surprised at how many people have claimed they aren't using them and have no idea what they were but actually did start using them for some reason or another

rocky canyon
#

u dont have the VSCode package installed do u?

#

as well as having this updated to the newest version?

#

sometimes when my IDE wigs out like that I can delete the csproj file and restart unity and it fixes it

wheat rune
#

deleting the .csproj worked, thanks guys

rocky canyon
#

good to hear!

#

sometimes Cinemachine does that to me so thats the reason I knew of (a) fix

glad quiver
#

If I use code to dynamically change tiles in a tilemap during runtime (like a player character editing terrain for example), do the rule tiles dynamically update and apply to all changes or do I need to code the changes to the surrounding tiles manually?

#

Basically, do tile rules apply in real-time during the game or only while initially painting the tilemap?

rocky canyon
#

rule tiles are for painting the tiles

#

changing them during runtime wouldn't apply

flint python
glad quiver
#

Dang. Thank you. I saw someone on YouTube using this technique and their tiles updated automatically and they didn’t mention how except to say “the rule tiles handle the rest” or something like that. I was skeptical but hopeful

swift crag
#

I'm pretty sure they work at runtime...

#

painting tiles is equivalent to calling SetTile

glad quiver
#

Oh hm… now I’m confused lol. I guess I could test it by making a mini game and seeing what works. Pita though.

swift crag
#

I will go check it

glad quiver
#

That would be so kind of you. Don’t put yourself out though

swift crag
#

yeah, it works fine!

#
    void Start()
    {
        BoundsInt bounds = new(-2, -2, -2, 4, 4, 4);

        foreach (var cell in bounds.allPositionsWithin)
            tilemap.SetTile(cell, ruleTile);
    }
#

just set a bunch of tiles through a script

#

(in hindsight, this was trying to set tiles in a cube, which doesn't really make sense for a 2D tilemap)

glad quiver
#

@swift crag wtf you are amazing, thank you! I dunno how you even did it that fast, I was expecting it to be a whole big thing.

swift crag
#

no problem (:

#

I'm still learning 2D, but I've been doing a lot of scripted tile setting

#

hadn't actually used rule tiles yet though

flint barn
#

Hello! I'm trying to do twitch integration on Unity and I'm having trouble making it so that if someone does a command for their avatar on stream, it only does it for that avatar and not all of them. I was attempted to use a concept of checking all the avatars in the list and whichever avatar name matches someones name who is doing the command, it does whatever. However, I've run into an issue because the avatar itself is a clone of a prefab and thus it's looking for that original prefab.

timber tide
#

if you instantiate a prefab instance you should have its own independent reference

#

are you not storing these reference, or probably post what code you have

timber tide
#

what is player

flint barn
#

Player is the prefab that all the avatar copies are made from

#

but specifically the var Player is the rigidbody2D of the prefab

timber tide
#

!code

eternal falconBOT
timber tide
#

not really enough information from that. Need to know where player is being created, and how those instances are being handled

#

once an object is instantiated, the changing the prefab should not reflect those that were previously instantiated by it

flint barn
timber tide
#

I don't see you instantiating player anywhere. You're just using the serialized reference that you inserted from the editor it seems.

#

so I'm not really understanding where these multiple players come from

#

You do make avatars, whatever those are. But player is a member value here and you only access that specific instance

rocky canyon
#
            if (layers != 0) // Check if enum set to a specific layer mask
            {
                // Raycast with the specified layer mask
                if(Physics.Raycast(transform.position, targetDir, out tempHit, rayDistance, layers))
                {
                    hitObject = tempHit.collider.gameObject;
                    hitPosition = tempHit.point;
                    success = true;
                }
                else
                {
                    hitObject = null;
                    hitPosition = Vector3.zero;
                    success = false;
                }  
            }
            else
            {
                // Raycast without specifying a layer mask, hitting all layers
                if(Physics.Raycast(transform.position, targetDir, out tempHit, rayDistance))
                {
                    hitObject = tempHit.collider.gameObject;
                    hitPosition = tempHit.point;
                    success = true;
                }
                else
                {
                    hitObject = null;
                    hitPosition = Vector3.zero;
                    success = false;
                }
            }``` this lookin uber repetitive to me. whats a good way to simplify this?
timber tide
#

can probably stick the else into its own method but other than that you're using two different filters

#

it's like one of those things you just toss into copilot for an opinion

eternal needle
flint barn
rocky canyon
#

just an enum

#

meant to be editor friendly

eternal needle
#

yea i would just swap this logic around. You're checking if its set to "nothing" but instead you could just use some local value which includes all layers

rocky canyon
#

i have a similarity on another set of variables

#

but they were as chunky in the comparison.. i just used a ternary for it in awake

rocky canyon
#

soo.. i could do the two, or a bool maybe

eternal needle
#

if its 0, set it to include everything. else just use the editor value
then do your raycast ALWAYS from layersToHit

#

this removes the need for the if else

rocky canyon
#

see... thats an epic thought

#

lol.. soo simple

flint barn
#

Hello, so I was able to make it so that a person in chat will only move their avatar that is on screen. However, now it's making it so the previous person's avatar can't move theirs. I believe it's due to the fact that "spawned" is only attached to the most recent spawned avatar. I'm not sure how I can loop through all created avatars and check to see if the person making the command is the owner of a specific avatar. I've attempted a simple loop that looks through a list of avatars but I continue to get stumped on how to apply it. https://hastebin.com/share/ragezaqoqa.csharp

rocky canyon
# rocky canyon ```cs if (layers != 0) // Check if enum set to a specific layer mask...
        void PerformRaycast()
        {
            success = Physics.Raycast(targetObj.transform.position, targetDir, out tempHit, rayDistance, targetLayerMask);
            hitObject = success ? tempHit.collider.gameObject : null;
            hitPosition = success ? tempHit.point : Vector3.zero;
        }```
noice..
i used `targetLayerMask = layers == 0 ? Physics.DefaultRaycastLayers : layers;` in the awake to avoid that extra conditional in update
brisk kindle
#

Hi guys, i'm trying to change the texture of material by using material.SetTexture but it dont work. Anyone have any idea about this? My material use ArnoldStandardSurface!

#

My Func:

        {
            rend.material.SetTexture("_BaseColorMap", texture);
            Debug.Log("Floor Changed");
        }```
rocky canyon
topaz mortar
#

How would I detect Input.GetKeyDown(KeyCode.S) on an item gameobject, but only while hovering that item with the mouse?

keen dew
#

Do you already know how to check hovering on the item?

rocky canyon
#

u just have to combine the two...
if(isHoveringButton && Input.GetKeyDown..) or..

{
       if(Input.GetKeyDown...)
       {
               // do something
       }
}```
topaz mortar
keen dew
#

I don't know what you mean by option

#

If you already know how to do it by any means, you can just combine the two with && like scg showed

topaz mortar
#

maybe there's an easier way to check if an object is being hovered?

rocky canyon
#

all the hover mechanics stuff i remember doing it like u do, with an enter and exit bool change..
there might be tho. maybe someone would know

topaz mortar
#

yeah pretty sure I'm using PointerEnter & PointerExit, in code though, didn't add the component to the gameobject, but think it works the same

rocky canyon
#

mmhmm similar stuff

keen dew
#

You can do a raycast with ScreenPointToRay but if that's easier is up for you to decide

keen dew
#

Thanks ChatGPT

rocky canyon
#
        ray = new Ray(cam.transform.position,cam.transform.forward);
        if(Physics.Raycast(ray, out RaycastHit hit,distance, mask))
        {
            if(hit.collider.transform.TryGetComponent(out IInteractable interactable))
            {
                cachedInteractable = hit.collider.gameObject;
                if(Input.GetKeyDown(interactKey))
                {
                    interactable.Interact();
                }
            }``` i prefer Interfaces and Trygets
topaz mortar
#

I'll just stick with the pointer enter & exit lol

wraith hornet
#

how can i change struct values in unity ?

#
{
    public AgentData agentData;

    public void SetSpeed(float speed)
    {
        agentData.moveSpeed = speed;
    }
}```
adjust agentData = new AgentData doesn work too
summer stump
wraith hornet
summer stump
#

It should change this local copy owned by physicsagent

rocky canyon
#

debug agentData.moveSpeed; immediately after you change it

wraith hornet
#

i got it. thanks so much

flint barn
#

Hey guys, I have text that is attached to an empty child of my player. How would I go about making it so that it doesn't get reversed when the player goes the opposite direction?

rocky canyon
#

textsObject.transform.rotation = Quaternion.Identity;

#

could reset its rotation in update or something

#

could unparent it and have it just track the player's position with an offset added.. textObject.transform.position = player.transform.position + vectorOffset;

#

could have it look at the camera.. theres lots of ways lol

#

ohhh transform.rotation = camera.transform.rotation!

eternal needle
#

id say you are just reversing the wrong object in the first place, it can still be parented in such a way where the visual cube is a child under the actual moving player. Text can now also be a child under that. You swap those visuals around and it doesnt affect the text

rocky canyon
#

this too lol

flint barn
#

I'll try, thanks guys!

timber tide
#

I like to stick rotational constraints on them and link em to some gamemanager that doesnt rotate

rocky canyon
#

ah yea, cool component

queen adder
#

does manually resizing minimized window trigger an event?

brisk kindle
rocky canyon
#

hmm,cs Material newMaterial = meshRenderer.material; newMaterial.mainTexture = testTexture; meshRenderer.material = newMaterial; something like this normally works for me

brisk kindle
#

My Func:

        {
            Material newMat = rend.material;
            newMat.SetTexture(BaseColorMap, texture);
            rend.material = newMat;
            Debug.Log("Floor Changed");
        }```
rocky canyon
#

what if u used rend.sharedMaterial; not sure the difference in the two actually

#

if that doesn't work then idk.

brisk kindle
rich adder
#

why not just have the material already with correct texture

#

and swap materials

rocky canyon
#

that ^ would work too

#

ohh its a shadergraph material

#

ya, that might be a bit different on how u access the graph's properties

brisk kindle
rocky canyon
#

this thread seems to chagne it like u do.

#

id make sure ur variable is exposed and everything in the graph.. and it should work.. w/ settexture but unsure why it doesn't in ur case

#

ur _Reference is probably different

brisk kindle
#

maybe i need to create some material

#

oh, i figured it out. the last character in my nameID has not been capitalized catto
Sorry for my carelessness!

cosmic mural
#

im following a tutorial to add a gradient to a progress bar but when i click on the menu it doenst open, how can i open the gradient editor?

#

when i press it nothing happens

quick pollen
#

So I have a class called "ProjectileHandler", and I want to create a script which is basically an alternate version of it which is the exact same, except that it has a different method for moving, like "ProjectileHandler" normally moves the projectile in a single line, but the alternate version (lets call it "CurvedProjectile" sends it off in a way that it curves over time
Can I use inheritance for that?

#

i have something like this until now

#

in a way i want to extend it

#

basically be the exact same thing, but it also has curving

eternal needle
quick pollen
#

problem is that if I have this script enabled, the movement stops working

eternal needle
# quick pollen i decided not to go with that approach in the end

Either inheritance here is gonna be used to set a vector, being the next move direction that the projectile does.
Or it directly moves the object however it wants.
Im not really sure what you mean by that last line, all the movement related logic is commented out

quick pollen
#

ignore the inheritance messages actually

#

rn im having issues with rotating my projectile....

fickle wagon
#
    {
        if(Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
        {
            if(Input.GetKeyDown(KeyCode.Z))
            {
                Debug.Log("CTR + Z");
            }
        }
    }``` How can i detect CTR + Z key shortcut in unity runtime through script, I have tried this code but its not working , btw i'm building for web.
#

CONTROL + Z

quick pollen
#

my bad

#

tho i dont think itll allow

fickle wagon
#

Oh, I am not mac and pressing control is not working bcs i have pc keyboard

covert timber
#

Hello, do you know how to draw these spheres? I would like to debug 3d vector visually

fossil drum
covert timber
#

Its all I need thanks

#

by debug 3d vector visually I mean draw it in the scene so I can see where it is instead of looking in an endless list of vectors in the console 😃

quick pollen
#

How can I use rb.MoveRotation to rotate an object by x degrees per second?

#

the example on the unity documentation straight up doesnt work

eternal needle
quick pollen
#
    private void Awake(){
        //main = GetComponent<ProjectileHandler>();
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        Vector3 angleVelocity = new(currentDegreesToRotate, currentDegreesToRotate, currentDegreesToRotate);
        Quaternion deltaRotation = Quaternion.Euler(angleVelocity * Time.deltaTime);
        rb.MoveRotation(deltaRotation * rb.rotation);
    }```
#

it does nothing

#

and yes I wanted to rotate it in all directions

#

wait

eternal needle
#

look at the unity example again, the order of operators in your move rotation is different

quick pollen
#

im stupid, nevermind

#

i used the wrong parameter

#

yeah thank you

#

idk how i didnt notice

#

cuz like

#

using Transform ways to rotate it works perfectly

#

except when I have a rigidbody

#

in which case it ignores it

#

it is still being ignored

#

it works in one scene

#

doesnt work on other

#

the main problem is that I'm also setting velocities

#

but not in the same thing way/script

eternal needle
# quick pollen but not in the same thing way/script

you should be controlling the rb from a single place, just for ease when it comes to debugging stuff like this. Also for your issue above, its likely they both have different settings. Maybe the environment has friction or the player does. Hard to say without seeing the setup but shouldnt be so hard for you to go through and see whats the same

stray pelican
#

Hi! I'm a real beginner in unity and I am just trying to understand how a button works and idk why but my button don't do anything when I click it

eternal needle
stray pelican
#

haa this was important okay

#

nice it works thxx

frank zodiac
#

so i added an auto jump and it applies a force when the player enters its trigger

#

but after it applies the force, i cant jump anymore

#
[SerializeField] private float jumpForce;

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player"))
    {
        other.GetComponent<Rigidbody>().linearVelocity = new Vector3(other.GetComponent<Rigidbody>().linearVelocity.x, jumpForce, other.GetComponent<Rigidbody>().linearVelocity.z);
    }
}
verbal dome
#

How does your jumping work?

eternal needle
#

does that code even compile?

verbal dome
#

Also consider caching the rb value: var rb = other.GetComponent<Rigidbody>()

verbal dome
eternal needle
#

oh yea i just saw that

frank zodiac
# verbal dome How does your jumping work?
public void OnJump(InputAction.CallbackContext context)
{
    if (context.performed && isGrounded)
    {
        Vector3 newVelocity = new Vector3(rigidbody.linearVelocity.x, jumpForce, rigidbody.linearVelocity.z);

        rigidbody.linearVelocity = newVelocity;
        animator.SetBool("isJumping", true);
    }
}
frank zodiac
#

i just used linear

verbal dome
#

Angular velocity is the rotational velocity

#

Linear is positional

frank zodiac
#

makes sense

eternal needle
frank zodiac
#

yeah i thought that was the problem

#

ill try that, thanks

#

okay so the problem is that its not grounded anymore

eternal needle
#

hm some messages get deleted or my discord bugging?

quick pollen
#

why is it that even if my projectile is rotating, it doesnt change trajectory?

frank zodiac
#

my problem still isnt fixed tho

#

idk why its not registering the ground check

eternal needle
#

Add debugs, print out if your raycast is even hitting anything. If so, print out what its hitting, and if you're considered grounded after that.

verbal dome
quick pollen
verbal dome
#

Rigidbodies arent rockets by default

quick pollen
frank zodiac
#

so therefore the jump isnt applied

verbal dome
quick pollen
#

lord....

#

alright

#

how could I add it here?

#

i know I have to multiply it by transform.forward

verbal dome
#

You could multiply it with transform.rotation or rb.rotation

quick pollen
#

moveSpeed * transform.forward.z?

verbal dome
quick pollen
verbal dome
eternal needle
verbal dome
#

To rotate a vector

frank zodiac
quick pollen
eternal needle
quick pollen
#

because you cant implicity multiply those

verbal dome
quick pollen
#

nor Vector3 * Vector3

verbal dome
#

Use the correct values

quick pollen
verbal dome
#

rb.rotation * someVelocity

#

transform.forward * moveSpeed would work also

frank zodiac
#

Physics.Raycast(transform.position, -transform.up, 0.5f, groundLayer) how would i get the raycasthit for this?

quick pollen
#

riight true

verbal dome
frank zodiac
quick pollen
#

still no rotation.

verbal dome
frank zodiac
#

ohhh i found it

quick pollen
#

thats not good

frank zodiac
#

didnt know i needed to scroll down

verbal dome
quick pollen
#

rb.velocity = new Vector3(rb.velocity.x * rb.rotation.x, rb.velocity.y * rb.rotation.y, -moveSpeed * rb.rotation.z); at first

#

does nothing

#

rb.velocity = rb.rotation.eulerAngles * moveSpeed;

#

makes it move at mach 10

#

i probably need to normalize it actually

verbal dome
#

Yeah no, the first one doesnt work because rotstion is a Quaternion and wuaternion's xyz components sre not angles, and well it doesnt really make sense anyway

quick pollen
#

rb.velocity = rb.rotation.eulerAngles.normalized * moveSpeed; makes it go up

verbal dome
#

Why use Euler angles here?

quick pollen
#

still, in a straight line

quick pollen
verbal dome
#

Makes no sense either

quick pollen
#

you cant multiply a quaternion and a float

#

but you can a vector3 and a float

#

what do you suggest then?

verbal dome
#

Just do transform.forward * moveSpeed

#

Vector * float

quick pollen
#

hold up

verbal dome
#

What exactly did you type

quick pollen
#

i might know the issue

#

okay now it works

#

thank you!

#

the issue was that I checked if the velocity changes before applying it

#

it was my way of not having to change the velocity every frame