#💻┃code-beginner

1 messages · Page 560 of 1

errant rock
#

ok

lucid quiver
#

the Transform lookAt is still the player

#

and check if u conected the script to the main camera

errant rock
#

lemme get this on vid for ya

fickle plume
#

@steep obsidian !collab don't spam learning channels.

eternal falconBOT
#

:loudspeaker: Collaborating and Job Posting

We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
Collaboration & Jobs

steep obsidian
fickle plume
#

!kick 1323159891178819725 spam

eternal falconBOT
#

dynoSuccess babalolamahmud was kicked.

errant rock
lucid quiver
errant rock
#

oh

lucid quiver
#

also since ur camera is a child of ur manmesh parent u dont need to update camera position tho this is not suggested while using rigidbody lets at least get this working first

#

remove this line transform.position = lookAt.position + rotation * Direction;

#

and attach the script to camera

errant rock
#

so player movement on manmesh and camera move on main camera?

lucid quiver
errant rock
#

okay 1 sec

#

and then set both look at and player to man mesh?

lucid quiver
#

u can get rid of this whole paragraph

Vector3 Direction = new Vector3(0, 0, -distance);
        Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
        transform.position = lookAt.position + rotation * Direction;
lucid quiver
pliant abyss
#

Reading the action cessation.

errant rock
# lucid quiver u can get rid of this whole paragraph ```cs Vector3 Direction = new Vector3(0, ...

so it should look like this now?


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraMove : MonoBehaviour
{

    private const float YMin = -50.0f;
    private const float YMax = 50.0f;



    public float distance = 10.0f;
    private float currentX = 0.0f;
    private float currentY = 0.0f;
    public float sensivity = 4.0f;


    // Start is called before the first frame update
    void Start()
    {


    }

    // Update is called once per frame
    void LateUpdate()
    {

        currentX += Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
        currentY += Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;

        currentY = Mathf.Clamp(currentY, YMin, YMax);

        

        transform.LookAt(new Vector3(-currentY, currentX, 0));



    }
}

lucid quiver
errant rock
#

ok do I need to keep the * and ;?

lucid quiver
#
currentX += Input.GetAxis("Mouse X") * sensivity;
currentY += Input.GetAxis("Mouse Y") * sensivity;
lucid quiver
errant rock
#

I orignially tried to learn ue5 😭 quickly switched to unity 😂

rocky canyon
#

unity's a better playground

pliant abyss
rocky canyon
#

memory scares me about those languages

errant rock
rocky canyon
#

from what ive heard its more hands-on management

errant rock
lucid quiver
#

tbh java a c# are like pretty similar so it was easy for me to learn it

pliant abyss
#

I took a Java class for my intro. Aced it. C++ kicked my ass.

lucid quiver
rocky canyon
errant rock
#

I'm just hoping that when I eventually get the hang of this I can get graphics similar to ue5 especially fire and explosions

rocky canyon
#

u can..

pliant abyss
rocky canyon
#

Unity's HDRP pipeline is pretty good graphically

pliant abyss
rocky canyon
#

i use URP and i can get really decent looking graphics..

#

its not 1:1 like unreal's

#

but its passable

errant rock
lucid quiver
pliant abyss
rocky canyon
errant rock
#

ooooh

rocky canyon
#

pair that w/ some lights and tada

swift crag
lucid quiver
#

i keep forgetting this is look at fucntion

errant rock
#

I will say I do like 1 thing in ue5 over unity, camera, movement and basic animations are already implimented

lucid quiver
#
transform.LookAt(new Vector3(currentX, currentY, 0));```
rocky canyon
swift crag
#

using LookAt seems weird

rocky canyon
#

the reason i stopped using UE.. is b/c it feels Tailored..

#

u need to make things how they expect u to make things

errant rock
#

tailored?

rocky canyon
#

if u deviate..

#

then its troublesome

lucid quiver
swift crag
errant rock
#

ah

swift crag
#

It feels very strange coming from Unity

lucid quiver
#

ikr i have never used that

lucid quiver
rocky canyon
#

if i were you Gorth.. i'd spend a day or so just reading/watching tutorials about camera systems and cinemachine

#

its a very important topic

swift crag
#

What kind of camera movement are you trying to create here?

lucid quiver
#

here change the last line to this

rocky canyon
#

if u follow the lead of someone (in a tutorial for example) even if its not what u want.. at teh end..

#

u'll learn some things that are invaluable

errant rock
rocky canyon
#

for u to try to do a custom one

swift crag
#

I can't think of a way for LookAt to make sense with mouse input like that

lucid quiver
rocky canyon
#

mouse delta -> rotation

swift crag
#

LookAt will cause the transform to rotate to point at a specific position in the world

rocky canyon
#

LookAt was amazing when i first started learning..

#

now i despise it

swift crag
#

that doesn't make any sense; as you move around, your camera will rotate

lucid quiver
swift crag
#

It sounds like you want mouse X movement to yaw the camera (left-right) and mouse Y movement to pitch the camera (up-down)

#

Is that correct?

errant rock
rocky canyon
#

just try to follow one from start to finish..

#

dont selectively pick and chose what to paste together

#

thats gonna make for a bad time

#

until u learn more

swift crag
#

This method produces a rotation by a certain angle around an axis.

lucid quiver
#

even if i use regular camer i just do transform.localRotation= something

rocky canyon
#

see.. Quaternion method FTW!

#
        private void RotateCamera()
        {
            // get our input
            Vector2 inputValues = new Vector2(Input.GetAxisRaw("Mouse X"),Input.GetAxisRaw("Mouse Y"));
            inputValues = Vector2.Scale(inputValues,new Vector2(lookSensitivity * smoothing,lookSensitivity * smoothing));

            smoothedVelocity.x = Mathf.Lerp(smoothedVelocity.x,inputValues.x,1f / smoothing);
            smoothedVelocity.y = Mathf.Lerp(smoothedVelocity.y,inputValues.y,1f / smoothing);

            currentLookingPos += smoothedVelocity;

            // rotate the camera on it's X axis (up and down)
            transform.localRotation = Quaternion.AngleAxis(-currentLookingPos.y,Vector3.right);

            // rotate the player on it's Y axis (left and right)
            controller.transform.localRotation = Quaternion.AngleAxis(currentLookingPos.x,controller.transform.up);
        }``` i like `AngleAxis` too
swift crag
#
lookInput *= Time.unscaledDeltaTime;

yaw += lookInput.x;
pitch -= lookInput.y;

yaw = Mathf.Repeat(yaw, 360);
pitch = Mathf.Clamp(pitch, -87f, 87f);

Quaternion turnRot = Quaternion.AngleAxis(yaw, Vector3.up);
Quaternion lookRot = turnRot * Quaternion.AngleAxis(pitch, Vector3.right);

Here is a snippet from my humanoid brain.

#

Before anyone points it out: I divide mouse input by unscaledDeltaTime in an input processor. That line is correct.

errant rock
#

@lucid quiver tysm this is loads better!

lucid quiver
#

even if u dont implement cinemachine right now u should look into vecotor lerp to decrease the camera stutter

swift crag
lucid quiver
#

also having the camera as a child to a rigidbody is not ideal

bitter canyon
#

any idea why objects are showing behind my canvas dexpite the z level

rocky canyon
#

real quick... my brain cant comprehend atm..
this is for my god cam... zooms in and out and pans..

question: does this line make it pan slower when zoomed in.. or faster when zoomed in?

rocky canyon
#

UI, Sprite, what?

bitter canyon
#

anything, sprites, uis

rocky canyon
#

Canvas is always rendered on top of everything

#

like an Overlay..

bitter canyon
#

its part of the canvas

rocky canyon
#

if u dont want that to be the case.. u need to use a world-space canvas

#

or an overlay canvas

swift crag
rocky canyon
#

if its part of the canvas then Hiearchy Order

#

is what manages it

swift crag
#

and this looks like a screenshot from the scene view

#

(but yes, an overlay canvas draws on top of everything -- it isn't rendered along with the rest of the scene)

errant rock
bitter canyon
errant rock
#

have the character rotate side to side with the camera even when not moving, coz atm if I don't move the character the camera feels completly seperated

slender nymph
# bitter canyon

SpriteRenderer is not a canvas object. if you want that on the canvas it should be an Image component

bitter canyon
#

oh i removed image before because i wanted a way to disable its visibility without deactivating the game object

slender nymph
#

you can disable the Image component too

lucid quiver
bitter canyon
lucid quiver
slender nymph
errant rock
#

camera shite coz i'm dumb

rocky canyon
#
        if(Input.mouseScrollDelta.y != 0)
        {
            newZoom += Input.mouseScrollDelta.y * zoomAmount;

            // Clamp the Y axis for vertical zooming (5 to 100)
            newZoom.y = Mathf.Clamp(newZoom.y,5f,100f);

            // Clamp the Z axis for depth zooming (-5 to -100)
            newZoom.z = Mathf.Clamp(newZoom.z,-100f,-5f);
        }```
#

ew.. hard coded values lol

bitter canyon
slender nymph
#

are you missing a using directive
make sure your !IDE is configured so you can add the correct using directive with the quick actions

eternal falconBOT
bitter canyon
#

good news: it works
bad news: big

slender nymph
#

yes well your scale previously was pretty huge

bitter canyon
#

i might want to tone that down

mystic lark
#

How do you set up the scren resolution i finished the game and when i gave i to my friennd who has a smaler monitor he couldnt see most of the things and also my game was a little odd stuff was smaller and wasnt where i placed them is there a tutorial or smth?

swift crag
#

You had sprite renderers on your canvas originally, right?

In that case, the default PPU (pixels per unit) of 100 would mean that 100 pixels of sprite take up one unit of space.

On an overlay canvas, one unit corresponds to one on-screen pixel

#

So everything is going to be 100 times larger now!

bitter canyon
vague pier
#

uhm, guys? I am making a drag and drop into my inventory yet it does not work properly, for example the item that I want to drag at (1|1)... if I drag and drop it, instead the item at (2|6) moves like my mouse needs to be on a whole different position. I already have screen space - overlay, I checked the content position etc

wintry quarry
short hazel
swift crag
slender nymph
# mystic lark thanks

also if you're using an orthographic camera (which would be typical for 2d games that don't need depth perception), you will want to also look into how to calculate the desired orthographic size for the camera to ensure it is the correct size. and supporting different aspect ratios without showing extra content would need letter boxing

swift crag
#

(notably, Cinemachine can do this for you (: )

mystic lark
#

thanks all now i need to learn all this stuff

vague pier
# wintry quarry We would have to see code...

using UnityEngine;
using UnityEngine.EventSystems;

public class DraggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler,IPointerDownHandler
{
[SerializeField] private Canvas canvas;
private RectTransform rect;

private void Awake()
{
    rect = GetComponent<RectTransform>();
}
public void OnBeginDrag(PointerEventData eventData)
{
    Debug.Log("hehe");
}

public void OnDrag(PointerEventData eventData)
{
    Debug.Log("haha");
    rect.anchoredPosition += eventData.delta /canvas.scaleFactor;
}

public void OnEndDrag(PointerEventData eventData)
{
    Debug.Log("hoho");
}

public void OnPointerDown(PointerEventData eventData)
{
    Debug.Log("Pointing");
}

}

#

but on other tutorials it works perfectly

#

but on mine it does not

vague pier
rocky canyon
#

a setup issue most likely..

#

do u have an EventSystem in the scene?

vague pier
#

but how though? yeah

rocky canyon
#

and a Graphics Raycaster

vague pier
#

yes

swift crag
#

or moves faster, perhaps?

rocky canyon
# vague pier yes

just checking.. those are the two normal culprits.. ppl forget to add them

vague pier
#

both it registers graphic raycaster but on utterly different position, its not about movement, its about position, I have to use my mouse far next to my item instead of on it

spark sinew
#

hi y'all, a quick question: when I do transform.position for a cube, is it the position of the center of the cube?

#

or is it the position of one of the vertices ?

wintry quarry
spark sinew
#

good

#

pheew

wintry quarry
#

It's whatever the origin of the mesh is

spark sinew
#

ok

slender nymph
wintry quarry
# spark sinew ok

As long as your tool handle position is set to "Pivot" you will see the position in the scene view when the object is selected.

vague pier
#

like very much

spark sinew
#

Thanks, also I may not be very sharp (unlike C sharp), but if I want to define a target and the renderer, I cannot define it in the declaration? I have to define it every time step in the update process ?

#

for example I was putting this before the void start thing, but apparently it is not good

#

private double X2t;
private double Z2t;
private Target = GameObject.Find("Target");
private rend =Target.GetComponent<MeshRenderer>();

swift crag
#

You can't use things like GameObject.Find in a field initializer

#

That winds up running at very interesting times

spark sinew
#

so if I keep the same object how should I do ?

swift crag
#

like when unity is loading your scene

#

What you want here is a serialized field!

spark sinew
#

should I declare it both in the start and update sections ?

swift crag
#

You should assign a reference in the inspector, ahead of time

#

If this is a prefab that needs to reference an object in the scene, then see...

spark sinew
#

ooch, too complicated for me

#

I will just keep it as is

swift crag
#

this is...very simple, really

#

much less prone to blowing up than using GameObject.Find

mystic lark
vague pier
#

how can I show live or vid to show my problem?

lucid quiver
dim yew
#

my camera movement is incredibly stuttery as is my movement, any ideas why? hopefully this is the right channel for this

#

i coded this all from scratch and i'm very bad at 3d so there's likely something stupid

dim yew
#

will read this, tysm

vague pier
mighty compass
#

hey guys, one of my packages i think is an old version, but says its up to date, and theres no option to update it

rich adder
vague pier
#

how do I fix this bug? on item, I cant drag, I have to position my mouse differently

rocky canyon
#

since its nested..

#

im guessing its a scaling issue..

#

the actual button/collider is not where u think it is

upbeat tide
#

how can i use nature/soft occlusion shaders if i am using a urp 3d template?

vague pier
#

But, when I saw I am on scene, it is still within slot...

#

how else can I check it?

lucid quiver
rocky canyon
rocky canyon
#

enable the gizmo's

#

it should show the green square around w/e element u have selected in the hiearchy

vague pier
rocky canyon
vague pier
#

huh?

rocky canyon
#

should atleast show u the bounds of things..

vague pier
#

it doesnt show the bounds in my case

rocky canyon
#

without being able to see the bounds.. ur just guessing its all correct

#

all images have one

#

also, make it a habit to check the game-view and the scene-view when ur debugging and figuring things out..

vague pier
#

but in scene view

#

everything is perfect

#

yet the mouse only registers

#

when off

rocky canyon
#

then it could be the scaling of the game-view..

vague pier
#

ohh

rocky canyon
#

if the UI's anchors and stuff get messed up.. if its scaled higher than ur scene-view for example

#

for example.. (this is another thing i do quite regularly when making UI)

#

stretch and squash the heck outta the game-view and inspect the scene-view at the same time.. to make sure everything moves and scales how it should

vague pier
#

still not working but again tysmm

sinful flame
#

Hey, I'm looking to recreate a grappling hook like the one in the right video. I've got a prototype working (left), but now I want to make it collide and bend around obstacles. How would you recommend I go about it? Should I:

  1. Make the line out of a chain of joints
  2. Dynamically create joints based on where the line collides
  3. Something else?
    The line can shrink when the player holds LMB, so I feel like 1) would be a little cumbersome. But with 2), I'm not sure if it could handle more complex shapes. Any tips?
rocky canyon
swift crag
sinful flame
#

awesome, that's the keyword i was looking for, thanks!

rocky canyon
#

reminds me of Worms2 Roping mechanic

sinful flame
#

can it generalize to 3d?

rocky canyon
sinful flame
#

bless, thanks!

rocky canyon
#

save ya some time huntin

#

theres some better ones out there tho..

sinful flame
#

omg lifesaver 🙏 tysm

rocky canyon
#

this one looks smoother

#

but its 2d

#

verlet rope was a game-changer..

#

after trying to make realistic type ropes w/ hinge-joints and failing miserably

sinful flame
#

lmaoo i tried that a little bit and had the same result. i knew there had to be a better way

mighty compass
swift crag
#

You can check which version of unity you need in the package's documentation

#

mildly confusingly, it won't show you the version for the package version you've selected, but you can see it for the others...

mystic lark
#

If i set the aspect ratio to 16.9 and my friend has a difrent monitor than mine will he be able to play my game normaly will he see evertinhing normaly or will the object and the scene not be all visible?

slender nymph
#

was the information you received about that earlier not sufficient?

mighty compass
#

Assets\TextMesh Pro\Examples & Extras\Scripts\VertexZoom.cs(153,44): error CS0029: Cannot implicitly convert type 'UnityEngine.Vector4[]' to 'UnityEngine.Vector2[]'

I updated to unity 6, and this one script has like 12 of these errors, it's a engine script

#

what do i do with that xD, I have no idea what that script even does

north kiln
#

It's an example, if you're not using it then delete it

mighty compass
#

thankyou!

#

YES you guys are great, I can finally use Rpc

#

+1 @north kiln +1 @swift crag

mystic lark
# slender nymph was the information you received about that earlier not sufficient?

i did the anchors thanks for that but the cinemachine i just cant figure out i added it to the game and its normal but i dont know how to use it so that it adapts to the monitors ratio i cant find nothing on that everything is about tracking objects and stuff and its my first ever game without a tutorial i just want my friends to play it lolUnityChanLoom

slender nymph
#

you don't have to use cinemachine to do that. i gave you the keywords you can use to research how calculate the orthographic size manually

slender nymph
#

research how calculate the orthographic size manually

mystic lark
#

ok

slender nymph
#

you should learn how to use cinemachine though if you aren't using it. it will be better camera controls than you'd be able to make manually

mystic lark
slender nymph
#

right but you have to actually be using cinemachine for your camera. you can't just slap cinemachine into the project and expect it to do that automatically

swift crag
#

Cinemachine can move the camera so that a set of objects are all in-frame

mystic lark
mystic lark
mighty compass
#
using UnityEngine;

public class NetworkPlayer : NetworkBehaviour {
    // Networked variable for health
    [SerializeField]
    private NetworkVariable<int> health = new NetworkVariable<int>(100); // Default health

    private void Start(){
    }

    private void Update(){

    }

    [Rpc(SendTo.Server)]
    public void reqMovePlayerRpc(){
        GameObject playerCamera = gameObject.transform.GetChild(0).gameObject;;
        Vector3 movement = Vector3.zero;
        Vector3 camForward = playerCamera.transform.forward;
        Vector3 camRight = playerCamera.transform.right;

        if (IsClient){

        }
        movePlayerRpc(direction);
    }
}
``` So I am trying to call a method on the GameManager object that takes care of serverside logic, but the client cant find the method, how do I make it so the client can find the method, should I search for the gamemanager object and then find it's script, and call the method like that?
slender nymph
#

you do not appear to have a movePlayerRpc method declared on this class. do you perhaps mean to call it on a reference to another object?

mighty compass
#

movePlayerRpc is declared on my GameManager object, I'm trying to invoke that method with parameters sent by a client, so that the server (GameManager) can reply with an updated position for the player

#

I'm just not sure what the best way to do this is

slender nymph
#

right, and because it is not on this object, you need to call it on that object. just calling movePlayerRpc(direction); is the same as doing this.movePlayerRpc(direction); but again, this does not have that method. so get a reference to the object that does. and maybe consider learning how c# works before attempting to do multiplayer

mighty compass
#

Lol I know how c# works buddy, unsure of how this multiplayer module works though, that's why im checking.

slender nymph
#

your issue has nothing to do with multiplayer and everything to do with calling a method on the wrong object

mighty compass
#

I was thinking that there must be another way, because giving the client a reference of the server object, and it's scripts sounds like a bad idea for security sake

slender nymph
timber tide
#

I'm not even seeing where some of those variables are being declared

slender nymph
#

the only things that are not declared are movePlayerRpc and direction

mighty compass
#

rest of the code doesn't matter, the only part im trying t ofigure out is calling the method on the gamemanager object without giving the client a reference of it

#

the rest of the code is unfinished, i mmigrating single player code to multiplayer

timber tide
#

Oh yeah im blind I see them ;p

slender nymph
#

my guy, these objects are all on the client too. just like literally anything else in c#, if you want to call a method on a specific object then get a reference to that object

mighty compass
#

alright thanks haha

errant rock
#
var speed: float = 5; // units per second
var turnSpeed: float = 90; // degrees per second
var jumpSpeed: float = 8;
var gravity: float = 9.8;
private var vSpeed: float = 0; // current vertical velocity

function Update(){
  transform.Rotate(0, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0);
  var vel: Vector3 = transform.forward * Input.GetAxis("Vertical") * speed;
  var controller = GetComponent(CharacterController);
  if (controller.isGrounded){
    vSpeed = 0; // grounded character has vSpeed = 0...
    if (Input.GetKeyDown("space")){ // unless it jumps:
      vSpeed = jumpSpeed;
    }
  }
  // apply gravity acceleration to vertical speed:
  vSpeed -= gravity * Time.deltaTime;
  vel.y = vSpeed; // include vertical speed in vel
  // convert vel to displacement and Move the character:
  controller.Move(vel * Time.deltaTime);
}

If I add this to my character movement script would it correctly implement gravity so that my character doesn't float and can actually interact with the ground?

vague sequoia
#

Why is the camera in another position far from where it should be?

errant rock
#

what does this mean?

wintry quarry
slender nymph
errant rock
#

!code

eternal falconBOT
errant rock
slender nymph
errant rock
#

^ the code

slender nymph
wintry quarry
slender nymph
#

and var is not a valid field type

wintry quarry
#

You should learn the basics before trying to jump into a game

errant rock
#

ffs I got it from a unity tutorial 🤦

slender nymph
#

you should use a tutorial from sometime in the last decade

errant rock
wintry quarry
errant rock
#

it was posted in 2012 😭

wintry quarry
lucid quiver
# errant rock oh shit

try sebastian lague's tutorial its a bit old but he explains things in a very begginer friendly way

slender nymph
# vague sequoia

now show it at runtime. and don't crop the screenshots so that half the useful information is hidden

lucid quiver
#

u can just use addforce no?

slender nymph
#

no because they appear to be using a CharacterController

vague sequoia
slender nymph
#

of course there are hundreds of modern CC movement tutorials that include gravity, so i have no idea how they managed to get one from 2012

lucid quiver
#

if ur a beginer maybe try learning a bit of the basics of c# first it will definitely help

steep rose
#

Google let you down

#

I suggest you google some more

lucid quiver
#

try youtube next

slender nymph
# vague sequoia

click the CameraPosition object assigned in the variable there and see what it highlights

lucid quiver
#

also did unity used to use js?

#

like what is this code?

slender nymph
#

yes, but support for it was dropped a decade ago

timber tide
#

https://assetstore.unity.com/packages/essentials/starter-assets-thirdperson-updates-in-new-charactercontroller-pa-196526
Unity has some templates you can rip apart. Most use the character controller component

Get the Starter Assets - ThirdPerson | Updates in new CharacterController package package from Unity Technologies and speed up your game development process. Find this & other Essentials options on the Unity Asset Store.

lucid quiver
#

character controller isnt very difficult once u get a hang of it but its not something i would start with if i didnt know the basics ... just try the old input system first

errant rock
#

Raziel that camera script u helped w earlier, do u know why I can only look 180 degrees? I cant look behind my character to spin him around

slender nymph
# vague sequoia

oh you know what, your tool handle is set to Center rather than Pivot. so you aren't seeing that the object that has this component is in the correct spot. it's your camera that is offset from that

lucid quiver
#

probably thats the issue

#

this is what happens when u copy code without understanding it

#

remove the clamp if u want full rotation

errant rock
#

I'm guessing cinemachine would fix all these issues?

lucid quiver
errant rock
#

fuck it how do I install it

lucid quiver
#

package manager

errant rock
#

bet

mighty compass
#
        playerCamera = gameObject.transform.GetChild(0).gameObject;;
        movement = Vector3.zero;
        camForward = playerCamera.transform.forward;
        camRight = playerCamera.transform.right;

        if (IsClient){
            // Calculate movement based on input keys.
            if (Input.GetKey(forwardKey)){
                movement += camForward.normalized * moveSpeed;
            }
            if (Input.GetKey(leftKey)){
                movement += -camRight.normalized * moveSpeed;
            }
            if (Input.GetKey(backwardKey)){
                movement += -camForward.normalized * moveSpeed;
            }
            if (Input.GetKey(rightKey)){
                movement += camRight.normalized * moveSpeed;
            }

            gameManagerScript.movePlayerRpc(movement, clientID);
        }
    }``` ```    [Rpc(SendTo.NotServer)]
    public void movePlayerRpc(Vector3 movement, ulong clientID){
        if (IsServer){
            NetworkObject playerObject = NetworkManager.Singleton.ConnectedClients[clientID].PlayerObject;
            Rigidbody rb = playerObject.GetComponent<Rigidbody>();
            // Set the Rigidbody's velocity for snappy movement.
            rb.linearVelocity = new Vector3(movement.x, rb.linearVelocity.y, movement.z);
        }
    }``` Im confused why this isn't working, Im sending movement data to server, server responds by moving the player, but im not sure why it has to send info out again afterwards
slender nymph
mighty compass
#

NVM FIGURED IT OUT YES

#

thx

queen adder
#

is there a trick to display the Scene class into the inspector? So you can LoadScene(sceneField)

#

it's atleast less prone to failure caused by renames/reorder in scenelist

slender nymph
#

there are assets that make it easier to do that, or you can write a property drawer for int or string that displays the scenes in the build list as a dropdown (which is what most of the assets like NaughtyAttributes does)

#

but the Scene itself is a SceneAsset which is a type from the UnityEditor namespace so naturally it won't be available in the build

queen adder
#

makes it a little clearer why unity didnt display it by default yet

forest summit
slender nymph
#

it doesn't look like a layermask issue, it looks like you are trying to check for a tag that does not exist

forest summit
#

i have a "Points" tag set on the coin

#

did i write something wrong?

slender nymph
#

show it, because it apparently does not exist

forest summit
rich adder
#

tags != layers

slender nymph
forest summit
#

oh

#

yeah

wintry quarry
mighty compass
#

kk

untold shore
#

Hey, quick question. I'm having some difficulty, and my code is calling a 'stack overflow'. Whenever I search it up it keeps coming out as it calling back to itself, whenever my code is going to different gameobject scripts (hopefully). Here's the code that its saying is having the stack overflow:

dealerCardValueonHand = Dealerhand.GetComponent<DealerCardValue>().handValue;

(Note, this is in a script called 'DealerDeckManager', and is on a DealerDeckManager object. DealerCardValue is on the DealerHand object.) If it helps, here is the DealerCardValue script:

    [SerializeField] public int handValue = 0;
    public TMP_Text dealerHandValueText;
    
    public void Update()
    {
        dealerHandValueText.text = "DealerHandValue: " + handValue.ToString();
    }``` Any ideas of how to fix this? I've never had this kind of error, so that's why I'm confused.
slender nymph
#

can you show the full stacktrace for that exception

untold shore
#

(whenever you do have a chance to respond, can you @ me? I have to do something, and may not be able to check if I have a response. Thanks!)

ripe shard
untold shore
#

It's not? Whenever I click on it it transports me to this

 public void DealerDrawCard()
    {
        playerDealCardButton.SetActive(false);
        playerStandButton.SetActive(false);
        playerSpecialCardButton.SetActive(false);
        dealerCardValueonHand = Dealerhand.GetComponent<DealerCardValue>().handValue;```
ripe shard
#

stack overflow happens typically when you call a function recursively, a common one is an event triggering itself (possibly indirectly)

untold shore
#

Oh, I see it now. Thank y'all so much!

ripe shard
untold shore
tough trench
#

I am new to unity and trying to make a fishing game. I want each fish to have multiple values what is the best way to do this?

robust condor
#

ScriptableObjects

wintry quarry
tough trench
wintry quarry
#
public class Fish : MonoBehaviour {
  public int SellValue;
  public string ID;
  public string Name;
}```
#

you can make prefabs with this script on them

#

and set the values as you wish for each one.

#

you could also use ScriptableObjects as Zyme mentioned, with similar fields

tough trench
#

ok thanks

obsidian plaza
#

i used scriptable objects for items and enemies and dungeon generation variables etc in my project and i dont get the hype

#

dont think ill do it again

robust condor
#

lol :F

cloud matrix
#

public class Explosive : MonoBehaviour
{
    private float health = 10f;
    public GameObject explosiveObject;
    public ParticleSystem explosionParticle;
    
    public void TakeDamage(float amount)
    {
        health -= amount;
        if (health <= 0f)
        {
            Explode();
        }
    }

    void Explode()
    {
        Destroy(explosiveObject);
        explosionParticle.Play();
    }
}

any reason why this isnt working?

cloud matrix
#

i fixed it its okay

#

cause i was using the same function for other targets that werent explosives, so it wasnt disappearing since it uses a different script

#

im smart trust me 😅 (im not)

#

nvm i fixed it, just had to add this line of code

explosionParticle.transform.parent = null;

tawny grove
#

How can i access and copy/past structures made with tile maps within scripts? for example, if i had this structure(image 1) within this tilemap(image 2), within a script, would it be possible to clone this structure without creating a new tile map or doing it through .settile?

wintry quarry
pulsar trail
#

I got the error: MonoScript could not be found
and i figured out that it can only be used in Unity Editor but not in runtime application

I am using MonoScript like such

class Skill {
    int atk;
    virtual void when_turn_starts() {}
    ...
}

and make a script for different skills
and attach them to corresponding scriptableobjects

how can i have access to the scripts in runtime app?

wintry quarry
tawny grove
tawny grove
#

alright, thank you!
last question, is it possible for me to divide areas/structures in a single tilemap into seperate objects (whilst still being in that tilemap)?

wintry quarry
#

A tilemap is a single component on a single GameObject

#

so no, that doesn't really make sense.

tawny grove
#

alright, ty

pulsar trail
echo kite
#

can someone help me open script

#

it needs visual studio

#

i think i opened

burnt vapor
# echo kite i think i opened

It is very unclear what you want. If you want to open scripts, I suggest you follow one of the many tutorials of properly setting up Unity with Visual Studio as the !ide

eternal falconBOT
echo kite
#

how did he get different options in camera?

burnt vapor
burnt vapor
#

People will help you with the code when able to

#

I'm not sure what you mean with "punishes that amount of buttons and weapons has to be the same but it already is"

orchid yoke
#

i need help too 💀

burnt vapor
eternal falconBOT
echo kite
#

what does this mean and how do i fix

obsidian plaza
#

at the top you must have accidentally deleted the monobehavior part or if you are following a tutorial then you are misusing the script

orchid yoke
#

hi i have a problem, im trying to do a multiplayer game but the two characters are confusing movements, even tho im moving lets say player one it moves the secpond one, it seems that only one player moves although im playing from the other one

#

also the camera glitches too

#

ok nvrm i fixed it

west radish
echo kite
#

now i deleted it and readded it but it still doesnt work

obsidian plaza
echo kite
languid spire
echo kite
languid spire
#

exactly what I said, perhaps you should learn some c# basics before continuing

frosty hound
#

What tutorial did you follow to create what you made here?

languid spire
echo kite
# frosty hound What tutorial did you follow to create what you made here?

https://www.youtube.com/watch?v=VF9UUixCvUs&t=112s&ab_channel=ChargerGames i changed sky added plane and circle colored it and now im putting movement script

Build 6 Full Games With Unity 2023 : https://bit.ly/3GUOYYh
(12+ Hours of Video Content)

Best Game Development Courses:

  1. Unity Android Game Development : Build 10 2D & 3D Games:
    https://www.udemy.com/course/unityandroidgamecourse/?referralCode=DCB2B7945CF67B1BDB67

  2. Unity By Example: 20+ Mini Projects (20+ Hours):
    https://www.udemy.com/un...

▶ Play video
frosty hound
#

Timestamp the part?

languid spire
obsidian plaza
#

my question is how do you see an error about a script and not even open the script to check

frosty hound
#

If there's a compiler error, Unity will show it in the console

echo kite
frosty hound
#

Nowhere in that timestamp does it look like anything you did. Maybe follow it?

white girder
grand snow
#

what is this enum im dumb its a layer mask

echo kite
#

at bottom

frosty hound
#

You made a script called PlayerController and you didn't modify it at all?

echo kite
languid spire
grand snow
frosty hound
#

Can you not see the difference in your script and their script? Just visually? It's extremely different.

echo kite
frosty hound
languid spire
languid spire
grand snow
#

public class PlayerController : MonoBehaviour

#

that is what it expects ^

white girder
languid spire
echo kite
# languid spire

i changed it after it didnt work because i incorrectly saw it in tutorial

echo kite
#

he put script in sphere first

frosty hound
#

Literally just watch the tutorial and copy their text. It is beyond simple.

languid spire
#

And delete all of the rubbish you have done already

echo kite
frosty hound
#

Alright good luck. Not wasting my time with this further.

languid spire
#

no, you still have too many scripts

echo kite
echo kite
languid spire
#

ok, so now change it to match the tutorial

languid spire
echo kite
#

wait

grand snow
#

@echo kite
public class PlayerController {} is WRONG ❌

public class PlayerController : MonoBehaviour {} is CORRECT ✅

echo kite
#

unity crashed

grand snow
#

everyone was trying to get you to see this clear error with how the script was defined. A new script made in the editor project window will have this format already.

echo kite
green flame
#

Hello, is there a way to read/check/uncheck an UI Toggle ? I tried do read the element like my Label:
```
Label name_1 = UIDocument.rootVisualElement.Q<Label>("BoostOneTitle");
name_1.text = "toto";

                var check_1 = UIDocument.rootVisualElement.Q<Toggle>("BoostOneCheck");
                Debug.Log(check_1.isOn);
            ```
            But isOn not working (I think I'm not correctly "declaring" my Toggle). Someone can tell me why it's not working please ? ^^
green flame
#

Ty it's working! But wtf the documentation say to use isOn xD
It's more possible that I don't understand fully the documentation 😛

languid spire
#

that is the UI docs not the UIToolkit ones

green flame
#

Aaah I found the other doc with ur keyword "UIToolkit" ! My bad ty very much I didnt knew that 😄

languid spire
green flame
#

Ty 😄

echo kite
#

wheres input manager

obsidian plaza
#

brother

burnt vapor
#

And please don't say that you don't know where to look, it's right there

languid spire
#

Also, not a code question

obsidian plaza
#

y screenshot and not read

#

i have to think abt my issue for at least 5mins before considering to ask here

gentle bone
#

thinking for just 5 minutes is like scrolling 5 minutes on tiktok... you should consider checking documents or doing a google search before asking for help.. probably like 1 hour or more hen you dont find a solution...

#

most problems are solved with a little search, but too much people are so lazy asking the simplest questions.. as if people today have an attenion span of 5 minutes..

steep rose
#

They do have an attention span of 5 minutes, which is quite wild

gentle bone
#

i probably ask for help after 3 days not fixing an issue or not finding whatr the problem is ^^

steep rose
#

maybe even less

languid spire
gentle bone
#

5 minutes today seem like a whole liefspan^^

steep rose
#

then bump it down to like 30 seconds (5 minutes was a bit generous)

gentle bone
#

i think sometimes people dont understand problem solving is the best part on development.. it opens your eyes to solutions you never thaught of...

grand snow
#

"Why read error when discord tell me answer"

gentle bone
#

why thinking when others can think for me^^ ..

languid spire
grand snow
#

I remember when I first was learning programming years ago. I read the java intro docs a lot and tried to do the official tutorials to learn. Now it's watch some random YouTube video and learn nothing...

quick fractal
grand snow
#

It's gonna get worse with AI generating crap people don't understand

quick fractal
gentle bone
#

as i started i loved to surf on stack^^

languid spire
grand snow
steep rose
quick fractal
rough lynx
languid spire
steep rose
#

Also I would like to have a C#, Java, and C++ (actually I have a C++ book 😅 ) hard copy at my disposal as they are extremely nice

languid spire
gentle bone
#

my first project ive done was directly a bot.. cause i hated the grinding part on Ragnarok Online ^^ it took a while till i got something to work but at the end it was my private bot.. never used by others.. so it was 99% undetected if i would get cuaght i knew it was my failure on coding...

steep rose
#

especially the understanding part

grand snow
#

I have a cpp book but I use cppreference mostly. Msdn is amazing for c# docs.

rough lynx
gentle bone
#

and i loved it.. i probably coded more on the bot as playing the game at that time.. everytime i ve seen a problem i tryed to fix it as fast i could... and it was a nice entry with cheat engine and a bit reverse engeinieering.. memory scanning etc.

languid spire
gentle bone
#

the dummys books where somehow nice to..

echo kite
#

input system?

steep rose
#

Read the error message, it points directly to it

echo kite
#

nvm

echo kite
#

now i found it

#

what do i do here

steep rose
#

you should see "Axes" which is a dropdown menu, drop it down then drop down Vertical and you should see the picture below (without Horizontal), you then would change "alt positive/negative and positive/negative buttons" to the respective value, you can probably just copy mine

grand snow
steep rose
#

Make sure you spell "Vertical" right in your code

rustic thunder
#

hello guys when i click my script and its supossed to take me to my script in visual studio it show nothing how do i fix that

rustic thunder
#

ik but it didnt work

languid spire
#

did it open VS?

rustic thunder
#

ya

#

😭

#

but nothing there

#

:((

grand snow
#

screenshot for us what "nothing" is

languid spire
#

so provide a screenshot of what it did do

#

btw, people who do cry and sob reaction emojis make themselves look like babies

frail hawk
hot laurel
#

#stop_IDE_go_nvim

languid spire
errant rock
#
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float jumpForce = 5f;
    public float groundCheckDistance = 0.1f;

    private Rigidbody rb;
    private Transform groundCheck;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        groundCheck = transform.Find("GroundCheck");
    }

    void FixedUpdate()
    {
        // Get input
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        // Calculate movement direction
        Vector3 movement = transform.forward * vertical + transform.right * horizontal;

        // Apply movement
        rb.linearVelocity = new Vector3(movement.x, rb.linearVelocity.y, movement.z) * moveSpeed;

        // Jump
        if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
        {
            rb.linearVelocity = new Vector3(rb.linearVelocity.x, jumpForce, rb.linearVelocity.z);
        }
    }

    private bool IsGrounded()
    {
        return Physics.Raycast(transform.position, Vector3.down, groundCheckDistance);
    }
}

Can someone help please I can't get jump to work

tough tartan
#

i was folliwng nattygamedev till i found he doesnt post anymore and quiot his tutorial so had to swtich to other channels to find how to implement guns and i think the looking around code from nattys is causing some issues with this new code and idk how to fix

#

code from input manager]

#

its not allowing me towalk around anymore and only makes me look

timber tide
#

kinda took a picture but missed out of the actual line numbers ;p

tough tartan
#

sorry sorry

timber tide
#

paste sites are better though if you do want quicker help

tough tartan
#

gotchu

tough tartan
timber tide
#

!code

eternal falconBOT
tough tartan
timber tide
#

just post the link

#

aight that's fine

tough tartan
#

this is the original input code

#

and then we alsogot the gun code which caused it to all go wrong

timber tide
#

Anyway, it does point to Fixed/Lateupdate and you don't really have much going on there, so start debug.logging those variables

#

something isn't being set and it's null

#

and when you're debugging values, make sure you debug left to right as you can't debug the dot operations if those too are nulll

tough tartan
#

so i did it again and my movement is somehow fine now?

timber tide
#

could been that you didnt save the script

tough tartan
#

maybe

#

thanks!

elfin zinc
#

How do I make custom keybinds using unity's input system package

golden oxide
#

hello i am wondering how people handle back buttons for their menus using keys specially ( their no actually button on the screen menu that says back ) for sub menu navigation one example can be any rpg maker game where you let say you press the equip button then it highlights the which equips slot you want to use (weapon, armor, boots, etc) , then after picking the slot it then takes you to inventory where all the weapon are stored and you can pick from but you want to return to slot selection to pick a different so you hit the b key to go back to that one section like an undo key , i have heard that the command pattern can help with that but I've not seen if it is used for menus or how it would be

tough tartan
#

anyone see why it isnt reloading when i hitthe r key

#

videoim following

#

player shootcode

eager elm
tough tartan
#

ill see

#

no its not

errant rock
#

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float jumpForce = 5f;
    public float groundCheckDistance = 0.1f;

    private Rigidbody _rb;
    private Transform _groundCheck;
    private Transform _cameraTransform;

    void Start()
    {
        _rb = GetComponent<Rigidbody>();

        if (_rb == null)
        {
            Debug.LogError("Rigidbody component not found on Player.");
            return;
        }

        _groundCheck = transform.Find("GroundCheck");
        _cameraTransform = Camera.main.transform;
    }

    void FixedUpdate()
    {
        // ... (rest of the script) 
    }

    // ... (rest of the script) 
}```

for some reason using a test project this code worked fine for wasd movement, but now it's in my main project it doesn't work at all
elfin zinc
#

would someone be able to help me in the thread i made

wintry quarry
#

also sharing the full script (in a paste site) would also be helpful.

queen adder
wintry quarry
errant rock
wintry quarry
#

in fact that's Microsoft's recommended convention for private members.

wintry quarry
queen adder
wintry quarry
queen adder
#

Aight, thanks lad

errant rock
wintry quarry
#

without an if statement

errant rock
#

sorry that was the wrong debug code lol I'm getting confused between my camera script and movement script now 🤣

wintry quarry
#

and no not "to the bottom", it should be the very first thing. We just want to see if the code is running at all.

errant rock
#

Okay gimme a min or 2

green flame
#

Re/Hello 😄

I created a Toggle in a UIDocument, but nothing happens when I click on the checkbox. Did I miss something ? Ty ^^

wintry quarry
errant rock
#

idk I added the debug thing, i think the script is running but isn't working

wintry quarry
#

show the code

errant rock
#

I think I'm going to just re-write the script

wintry quarry
errant rock
wintry quarry
#

// ... (rest of the script)

#

if this is your actual code obviously nothing happens

errant rock
#

why

wintry quarry
#

there's no code there

vocal orchid
#

Why the first condicional working, but the secund and third not working?

#
void FixedUpdate()
{
if (transform.position.y > 6.7f && transform.position.y < 7f)
                {
                    Debug.Log("Shoot bullet");
                }
                if (transform.position.y > -4.2f && transform.position.y < -4f)
                {
                    Debug.Log("Shoot bullet");
                }
                if (transform.position.y > -17f && transform.position.y < -17.2f)
                {
                    Debug.Log("Shoot bullet");
                }
}
wintry quarry
tulip nimbus
#
public ChestAnimation chest;
RaycastHit hit;

void Start()
{
    chest = FindFirstObjectByType < ChestAnimation >();
}


void Update()
{
    
    InteractionRay();
}

void InteractionRay() {


    Debug.Log(hit.collider);

    if (Physics.Raycast(transform.position, transform.forward, out hit, 10f)) 
    {
        

        if (hit.collider.gameObject.name == "TestChest") 
        {

            chest.Open();
            

        }
        else if (hit.collider == null || hit.collider.gameObject.name != "TestChest")
        { 
            chest.Close();
           
        }
        
    }
}

I want to make it, so that whenever nothing or somethjing else is being looked at, chest.Close is called. Hit.collider is debugged as "Null" However it does not call chest.Close().

wintry quarry
wintry quarry
# vocal orchid I haven't idea

so why did you say "Why the first condicional working, but the secund and third not working?" when you have no idea if the first one is working?

wintry quarry
#

get it from the raycast.

#

we want to know the chest your raycast hit, not any random chest in the scene

queen parcel
#

Hi, can anyone help with objects on different resolutions? Is there a code or a way to make the object automatically adjust to the screen size too?

vocal orchid
tulip nimbus
# wintry quarry get it from the raycast.
 if (Physics.Raycast(transform.position, transform.forward, out hit, 10f))
 {
     var chest = hit.collider.gameObject.GetComponent<ChestAnimation>();
 }

Would you do it like this, or differently? Im asking because i do not know how to trigger certain methods like Open() and Close() if chest is not defined in the code. Should i use Interfaces for this, or am i mixing up something completely?

slender nymph
wintry quarry
#

Not sure what you mean by "if chest is not defined in the code"

wintry quarry
gentle bone
#

and probably you dont need to raycast so far.. 10f..

#

50% or less would still be enough for most things... probably...

#

not much but still less performant... if you do that 100 times...

cosmic quail
wintry quarry
#

performance is really not a concern at the moment.

#

The distance should be whatever distance they want the game designed with

gentle bone
#

was just an advice.. if you learn it by beginning you learn it by doing

cosmic quail
#

is it true that bigger distance worsens performance?

wintry quarry
#

not always and certainly not linearly, but potentially, under the right circumstances, yes.

gentle bone
#

not much with the cpus today.. but if you do it 100x or 1000x times.. it will make a difference on the size of the scene and objects..

wintry quarry
#

but a performance discussion here is really derailing.

gentle bone
#

yeah sry..

#

but if you start early its better ^^

#

but i think the problem as ssen i just cam back before.. is that chest is local and you call it from somewhere else..

#

try call it from somewhere else

#

so you need to make it available..from outwards

vocal orchid
wintry quarry
vocal orchid
#

Depend the position in axe Y

cosmic quail
wintry quarry
#

You're not going to get effective help here if you come back once every 20 minutes with a 3 word answer that doesn't explain what's going on.

west radish
#

private static Spline _perimeter; Spline is a struct, and I need to destroy the instance, but I cant write

private void OnDestroy()
{
  _perimeter = null;
}```
#

what can I do to remove it?

slender nymph
#

Value types can't be null, best you can do is assign it default which is all of its bits set to 0

wintry quarry
#

Structs cannot be "destroyed"

west radish
#

just so it doesnt exist after I stop playing

wintry quarry
#

If this script is currently being destroyed (you're in OnDestroy) you don't need to do anything

#

it won't

#

Unless the struct is referring to some other thing, which would be the thing you actually need to destroy

#

You need to share more information here

#

we don't have enough context. What is this Spline struct? Where did it come from? Is it your custom struct? What fields does it have?

west radish
#

well setting it to default worked. It was just that when I stop running the game, I needed to make my static objects no longer exist

wintry quarry
#

Again it depends what those things are

#

if this struct has a reference to, for example, a UnityEngine.Object instance, you would want to call Destroy() on that instance, for example

west radish
#

its fine with everything else, it was just the struct having the problem

swift crag
#

It is not possible for a value type to "not exist"

#

because it's not possible for a field to "not exist", really

#

a value-typed field intrinsically contains the value (hence the name)

#

a reference-typed field just tells you where the actual object is (thus making it possible to have no object)

west radish
#

honestly, ive always found it a little difficult to know when to go with a struct or a class

#

I get the idea of structs

#

like when I've made my own Vector implementation in the past, its sensible those are always structs

swift crag
#

i guess you should interrogate why you made it a struct

#

one obvious answer is "holy shit that'd be a lot of allocations"

west radish
#

making my Spline be a struct seemed like the right idea before

swift crag
#

but that's a performance matter, and performance matters aren't satisfying

wintry quarry
west radish
#

yeah, class fits better for it

swift crag
#

I suppose it'd be better to ask why you don't think you need a class

#

If you ignore things like being blittable (i.e. you can copy a struct directly into unmanaged memory and it'll still make sense), structs don't unlock new functionality

#

They just impose a bunch of rules on you

rocky canyon
#

i just think of structs as simply data containers

swift crag
#

but that's a cop-out answer, I guess, because that's the entire distinction between a class and a struct 😆

rocky canyon
#

if its not strictly just data i use class.. but then again im noob 🫠

west radish
swift crag
#

It's shaped like itself

west radish
#

however a few things I was intending to do, ive decided against or figured out a better approach

#

Spline being a struct seems like its one of those things

#

also just noticed this is the beginner channel 😅

rocky canyon
#

seems fitting to me.. i still consider myself a beginner.. and found value from reading thru it

vocal orchid
#
using System.Collections;
using UnityEngine;

public class Enemy_2 : MonoBehaviour
{
    public float speed;
    public float points;
    public delegate void UpdateUI(float points);
    public event UpdateUI UpdateUIPoints;

    Rigidbody2D rb2D;

    [SerializeField] bool isMovingHorLeft;

    [SerializeField] bool isMovingHorRight;
    [SerializeField] bool isMovingVert;

    [SerializeField] GameObject burst;
    void Start()
    {
        rb2D = GetComponent<Rigidbody2D>();
        isMovingHorLeft = true;
        isMovingHorRight = false;
        isMovingVert = false;
    }

    void FixedUpdate()
    {
        if (transform.position.x > 19.5f && isMovingHorLeft && !isMovingHorRight && !isMovingVert && transform.position.y > 1f)
        {
            rb2D.AddForce(Vector2.left * speed, ForceMode2D.Impulse);
        }
        else
        {
            isMovingHorLeft = false;
            isMovingHorRight = false;
            isMovingVert = true;
            if (isMovingVert && !isMovingHorLeft && !isMovingHorRight && transform.position.y > -17.1f)
            {
                rb2D.AddForce(Vector2.down * speed, ForceMode2D.Impulse);
                if (transform.position.y > 6.7f && transform.position.y < 7f)
                {
                    Debug.Log("Shoot bullet");
                }
                if (transform.position.y > -4.2f && transform.position.y < -4f)
                {
                    Debug.Log("Shoot bullet");
                }
                if (transform.position.y > -17f && transform.position.y < -17.2f)
                {
                    Debug.Log("Shoot bullet");
                }
            }
            else
            {
                isMovingHorLeft = false;
                isMovingHorRight = true;
                isMovingVert = false;
                if (isMovingHorRight && !isMovingHorLeft && !isMovingVert && transform.position.y < -17.3f)
                {
                    rb2D.AddForce(Vector2.right * speed, ForceMode2D.Impulse);
                }
            }
        }
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "bullet_ship")
        {
            speed = 0;
            UpdateUIPoints?.Invoke(points);
            Destroy(gameObject);
            Instantiate(burst, transform.position + new UnityEngine.Vector3(0f, 2.06f, 0f), Quaternion.identity);
        }
    }
}


slender nymph
wintry quarry
#
            isMovingHorLeft = false;
            isMovingHorRight = false;
            isMovingVert = true;
            if (isMovingVert && !isMovingHorLeft && !isMovingHorRight && transform.position.y > -17.1f)```
What's the point of all of these bool variables? It seems like you are just setting them directly before checking their values. You can remove them completely in that case.
#

you KNOW isMovingVert is true and the horizontal ones are false because you literally just set them that way. THere's no point in having them.

rocky canyon
#

ifTrue;
ifNotTrue;

ya, the bools instantly complicate things like simple if statements

west radish
#

Fen helped out with it

wintry quarry
#

Anyway, as I've been telling you many times, add more and different log statements at different points in the code to see where your code is actually getting to. You can also print the actual values of things, like the object position, to see what's going on @vocal orchid

west radish
#

that code will do that

#

but for a number of reasons, that code will be very tough to maintain

west radish
#
void FixedUpdate()
{
  bool enemyMustShoot = false;
  bool enemyMustMove = false;
  
  ...
  ...
  
  if(enemyMustShoot) { Debug.Log("Shoot bullet"); }
  if(enemyMustMove) { rb2D.AddForce() }
  
}```
#

if you changed it to have a structure like this, it simplifies the way of setting up the conditions

#

if you ran this code, didnt have anything at the ... then it will never shoot and never move

#

the only goal is to find out what has to happen to make it do either outcome

vocal orchid
#

Yeah, simply

swift crag
#

Minimizing the amount of state is a great idea

#

Every field is something that can go wrong on frame X and then cause a problem on frame X+10000

left solar
#

I'm struggling with Local Co-Op multiplayer code. Specifically, item pickups (such as health, crafting materials, etc.) and each player's inventory. Anyone willing to give me a hand, let me know.

timber tide
#

Oh, unless you mean actual splitscreen co-op type of deal sorry

#

in that case, give the question here

left solar
#

Each player has an InventoryContainer Empty game object attached to them. Pressing Tab sets the inventory to active or inactive, and it has various slots to put items into.
I need a way to find out which player touched the Pickup, have the pickup reach out and talk to the inventory, whether or not it's open or closed, active or inactive, and then run the AddToInventory method.

I am having trouble:

  1. Detecting which player has touched the item.
  2. Getting that player's inventory, whether or not it is active or hidden.
timber tide
left solar
#

So far I've been using tags, and it's been working. The part I'm struggling with is mostly reaching out to that specific player's inventory.

slender nymph
#

Ideally you'd be handling the logic for picking up an item on the player instances so they should just have a reference to its own inventory

left solar
#

I see

wintry quarry
#

Ideally, all the players would also being using the same exact code/script

#

you should not have like a "Player1Movement" script and a "Player2Movement" script, for example

left solar
#

The pickups are prefabs, and the name, count, and sprite are determined by a script attached to them.

#

I have that going on. Each player is a prefab, with identical code

wintry quarry
left solar
#

what about OnTriggerEnter2D?

wintry quarry
#

yes

#

that's a collision callback

#

you can use that

#

OnTriggerEnter2D gives you a reference to the collider you interacted with

#

you can get from that collider to any other components you want on that object with GetComponent

#

and/or traversing the Transform hierarchy as needed.

left solar
#

Then the other major issue; the inventory empty not playing nice with being active or inactive. even with OnTriggerEnter2D, it seems like the inventory being inactive makes it completely impossible for it to be found and communicated with.

wintry quarry
left solar
#

I even struggled getting this to work with just 1 player.

wintry quarry
#

if you use GetComponent and/or traverse the transform hierarchy, it is not a problem at all

#

Really you just need a script on the root of the enemy that has a direct reference to the thing. Just interact with that one script.

left solar
#

I don't follow

wintry quarry
#

Put a script on the enemy

#

when you collide with the enemy you grab that script and do whatever you need to do

#
void OnTriggerEnter2D(Collider2D other) {
  if (other.TryGetComponent(out Enemy enemy)) {
    enemy.ShowInventory();
  }
}```
#

For example^

left solar
#

what is .TryGetComponent? I have never seen that in any of the Unity Tutorials I've been digging through.

wintry quarry
#
void OnTriggerEnter2D(Collider2D other) {
  Enemy enemy = other.GetComponent<Enemy>();
  if (enemy != null) {
    enemy.ShowInventory();
  }
}```
This is the same
steep rose
#

Getcomponent brute forces getting a component, so if there is nothing there it will give you errors

left solar
#

I see. it's very clean.

wintry quarry
#

yep

dusty chasm
#

Anyone know how to use IK rigging to hold items similar to games like Lethal Company. For some odd reason when I have it keep the arms targeted to the item in the players hands if I look too high up the item falls off the hands.

left solar
#

so, when the player touches a Pickup, it talks to its own inventory.
The player needs to get information about what the pickup's name, count, and sprite. Should the player reach out to the item, then?

wintry quarry
#

As for which way the information passes, that's up to you

left solar
#

ok, so the player should be reaching, and the pickup is essentially just a text file full of info as to what it is. the player then copies that info into their own inventory.

wintry quarry
#

that could work as a simple start, sure

left solar
#

the issue with the active/inactive inventory, OnTriggerEnter2D and TryGetComponent will still work if the inventory is inactive? IE, the player pressed tab so that their screen isn't covered by the inventory UI.

wintry quarry
#

But yes, TryGetComponent does not care at all

#

about things being active or not

left solar
#

ok, epic.

#

thanks for the help :^D

wintry quarry
#

Most likely you have coupled your inventory UI too closely to everything else

left solar
#

No, no. the UI is causing no issues. It works beautifully. It's just that while it is inactive I couldn't get the InventoryController script on it, and tell it what item the player just touched.

#

but if TryGetComponent works even on hidden objects, it should have no trouble reaching out to the Inventory and talking to the script attached to it, even while it's inactive.

slender nymph
#

TryGetComponent won't find another object. so if you're trying to replace some FindXXX call with it, that won't work. You can call TryGetComponent on something you already have a reference to in order to get a component from that object you have referenced.
It also sounds like you have your dependencies backwards. Your Player shouldn't rely on the UI for the inventory, the player itself (or some middleman object) should control the inventory and the UI should just reach out to that to display what is in the inventory

patent verge
#

How could I make my lighting actually dark? and my flashlight work a little better

slender nymph
patent verge
#

thank you sorry

slender nymph
#

also make sure to provide more info such as the actual settings on your light

rare elm
#

if i drop a GameObject on my main menu, and in its Start/0 I call Debug.Log(Input.GetJoystickNames()), I should see an array of strings of my joysticks, right? i ask because i bought some kit, and on their web demo the joystick works, but in unity editor it doesn't, despite that it looks wired up in the input manager, so i tried as mentioned and ... got an empty array. while using the joystick successfully in the web compile.

#

's very confusing

#

i even see reconnect and disconnect events in log for it. just ... not the controller in the name list.

rare elm
#

seems unity was just having a brain issue. rebooted the machine and everything works as expected.

broken plume
#

can anyone help me with a tilemap setting?
i want that the tile use only one slot instead of four or more

teal viper
broken plume
teal viper
broken plume
#

sec ill show you

#

this is my config for 2x2

#

if i set 400

#

it looks like this

teal viper
broken plume
#

okay thanks

#

i fixed it

mighty compass
#

Hey I need help configuring my ide

north kiln
#

!ide

eternal falconBOT
mighty compass
#

nvm igot it

bright sequoia
#

Trying to set up an inventory system from a tutorial, but he's starting from scratch and i'm starting from an existing project

This (image) is the code he has in the video, but I already have an interaction system in my game with Interfaces where when youre close enough to an object, you can press E to interact

I tried putting the tutorial code into mine (removed "other" as it didn't work with my existing code, but otherwise tried to follow the tutorial)

When I playtested, my object wasn't added to the inventory or destroyed. Anyone know how I can get back on track with the tutorial? pensive sorry I'm new to programming

{
    IInteractable activeInteractable;

    public InventoryObject inventory;
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.E))
        {
            if (activeInteractable is Component activeInteractableComponent)
            {
                foreach (IInteractable interactableChild in activeInteractableComponent.GetComponentsInChildren<IInteractable>())
                {
                    interactableChild.Interact();
                }
            }
            else
            {
                activeInteractable?.Interact();
            }

            var item = GetComponent<Item>();
            if (item)
            {
                inventory.AddItem(item.item, 1);
                Destroy(gameObject);
            }
        }
    }


    public void TapInteractable(IInteractable newInteractable)
    {
        activeInteractable = newInteractable;
    }
}```
proper field
#

After making this script my project froze and won't let me click anything on it what did I do wrong?

proper field
proper field
cosmic dagger
teal viper
cosmic dagger
#

also much easier for us to copy/paste and test it out ourselves, if necessary . . .

proper field
#

using UnityEngine;

public class burdscript : MonoBehaviour
{
public Rigidbody2D myRigidbody;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{

}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) == true)
    {
        myRigidbody.velocity = Vector2.up * 10;
    }   
}

}

#

That right or nah?

eternal falconBOT
teal viper
#

But no, there's nothing in your code that might freeze or crash unity.
However, your !ide is not configured properly, which might be related to the issue:

eternal falconBOT
bright sequoia
#

for future reference, how many lines of code is considered "large"

cosmic dagger
proper field
teal viper
cosmic dagger
teal viper
cosmic dagger
bright sequoia
#

I started programming less than a month ago so I can't sight-read code yet noooooooooooo lol

I think I figured out what I did wrong tho, thx

cloud matrix
#

so i cant see the body but other people can, because im making a multiplayer game

south rock
#

So I'm trying out a tutorial to make my first game. Its supposed to display the message in the console when hitting my obstacle (the black cube), but its not. When messing with the code I figured out its acting as though the player (red cube) is hitting the obstacle instead of vice versa. Someone please help...

#

By the last statement I mean that I made it at first where it would display the name of what object the player hit, and instead of it displaying "obstacle" it displayed "player"

#

Its messing my code up entirely

cloud matrix
south rock
#

Elaborate?

#

Sorry I'm slow ;-;

#

Oh, wait, I think I understand

#

Its on the obstacle

#

OMG NVM I GOT IT TO WORK I FEEL SO DUMB

proper field
wispy coral
#

yall is the OnMouseDown() method an individual method or is it part of one of the input systems?

cloud matrix
wispy coral
#

got it thanks

wintry quarry
wispy coral
wintry quarry
wispy coral
#

and what i meant was if its a individual method not linked to any input system

wintry quarry
#

What's the actual reason/motivation behind the question?

#

It's not part of the old input system but it only works with the old input system, is my understanding

wispy coral
#

watching a tutorial and they used OnMouseDown() and i wanted to know if it was part of the old input system since the whole course uses the old input system and im getting used to using the new one

wispy coral
#

ill have to investigate alternatives for that then

wintry quarry
#

OnMouseDown is effectively replaced with PointerDown/IPointerDownHandler which are part of the UI system.

#

(but still work with non UI objects)

wispy coral
#

seems fair

#

just need to delete a game object so its gonna be simple

#

thanks

#

and happy new year

acoustic sequoia
#

Hey Everyone, quick question: I'm trying to create a waypoint system for my 2D game, here's my current working code with a minor issue.

  {
    if (playerTransform == null) return;

    float maxScreenX = Screen.width - screenMargin;
    float maxScreenY = Screen.height - screenMargin;

    Vector2 pos = Camera.main.WorldToScreenPoint(targetTransform.position);
    pos.x = Mathf.Clamp(pos.x, screenMargin, maxScreenX);
    pos.y = Mathf.Clamp(pos.y, screenMargin, maxScreenY);

    transform.position = pos;
  }```
this doesn't represent well if my target is offscreen. let me explain, if my target is offscreen to the right and slightly upward.. (think of it as 2:00 on a clock) the waypoint should not be representing the icon at 2:00 on the screen border, instead somewhere between 2:00 and 3:00 since 3:00 is the center of my character in the horizontal direction. am i making sense ?

i can draw a simple picture if this doesn't make sense. let me know thanks!
#

i made the picture anyway. i want the waypoint icon to show on the green 'X' not the red 'X'

narrow shard
#

I just wanna present a game idea to someone

compact stag
#

hey guys! what you guys are seeing here is two box colliders, i dont want them to overlap and i want the outer hitbox to not overlap the inner hitbox (i hope it makes sense)

im not sure where to post this, but any help is welcome!!

teal viper
teal viper
compact stag
teal viper
compact stag
#

bounds?

acoustic sequoia
charred spoke
#

Why not just cover the outer area with 4 colliders ?

compact stag
charred spoke
#

The performance of calculating if you are in the big volume while also inside the small volume is arguably going to be worse

compact stag
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

teal viper
frail wind
#

guy can you tell me why both code got active? even tho i make a bool that make sure that both of them won't get active at the same time.

 if (Input.GetKeyDown(KeyCode.Q) && cursorLock == false)
 {
     Cursor.lockState = CursorLockMode.Locked;
     cursorLock = true;
     Debug.Log("lock cursor");
 }

 if (Input.GetKeyDown(KeyCode.Q) && cursorLock == true)
 {
     Cursor.lockState = CursorLockMode.None;
     cursorLock = false;
     Debug.Log("unlock cursor");

 }    ```
#

also i putting it on void update

minor island
#

Its Update.... so it's called multiple time per sec...

#

So during each call diffrent if statement is totally true, and its look for you like both are called

frail wind
#

then i have to place it on void start?

minor island
#

Input need to be on update

#

Cause you need to detect user input

#

Maybe add "else" before sec if?

frail wind
#

ok

north kiln
frail wind
#

it still execute both of them

if (Input.GetKeyDown(KeyCode.Q) && cursorLock == false)
{
    Cursor.lockState = CursorLockMode.Locked;
    cursorLock = true;
    Debug.Log("lock cursor");
}

else if (Input.GetKeyUp(KeyCode.Q) && cursorLock == true)
{
    Cursor.lockState = CursorLockMode.None;
    cursorLock = false;
    Debug.Log("unlock cursor");```
#

at the same time

north kiln
#

It's not at the same time, you changed it to GetKeyUp

pulsar trail
#

I would like to attach a script (i need the class inside) to a scriptableobject,
but monoscript is only available in unity editor not in runtime,
is there any way to attach a script to a scriptableobject?

keen dew
#

Sounds like there's a bit of conceptual misunderstanding there. You don't need to attach scripts anywhere to access classes.

tawny grove
#

does TilemapRenderer have a way to flip their full sprite(s) horizontally/vertically like normal sprite renders? flipX and flipY dont exist for them

white girder
lucid quiver
white girder
#

Whenever I do that it tells me to use linearVelocity instead of velocity Thinkge

west radish
#

Yeah, velocity isn't meant to be used anymore

#

It's outdated

white girder
#

Commenting out the line rgPlayer.linearVelocity = new Vector3(rgPlayer.linearVelocity.x, 0f,rgPlayer.linearVelocity.z); pretty much fixed the problem, still a bit inconsistent but its much less noticeable now happyface

errant pilot
#

if (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float t = elapsedTime / duration;
float x = Mathf.Lerp(startPosition.x, endPosition.x, t);
if (Mathf.Abs(transform.position.x - vertexX) < 0.1 && a == oldA)
{
a = (endPosition.y - vertexY) / Mathf.Pow(endPosition.x - vertexX, 2);
}
float y = a * Mathf.Pow(x - vertexX, 2) + vertexY;
currentPos = new Vector2(x, y);
transform.position = currentPos;
}

#

Guys im trying to make a parabolic motion and this is what i got but the object doesnt go to the end position it parabolically goes somewhere else

burnt vapor
tough plinth
#

Hello!
So I'm currently trying to finish Unity Essentials Pathways but kinda stuck on the last task which asks you to make a script that plays SFX when Blocks/Ball interacts with each other.

My block script works well, but ball SFX doesn't work for some reason. (2nd pic)

#

Any thoughts?

languid spire
#

you are comparing for the same tag on 2 different objects, is this correct?

#

and why would you compare tag on the object that these scripts are attached to

frail hawk
#

additionally to what steve said, you need to use if(collision.CompareTag("tag"))

#

did you not get any error messages

tough plinth
#

Uh, sec

tough plinth
# frail hawk did you not get any error messages

I did not. So, the idea was (seeing what was similar to Essentials Pathway), I decided to compare the tags, so for example, if something collides with blocks, they will make a sound. And since they are being knocked over by the ball, when they collide with each other, script checks it and plays sound

#

For some reason even if there is no block nearby and player touches one of the blocks, it still plays that sound, I have no glue how it works so perfectly

languid spire
#

but you are not checking what is being collided with

tough plinth
#

How can I do so?

languid spire
tough plinth
#

In pathway I saw (other.CompareTag("code lala"), but it does not work, why is that happening?

languid spire
#

because you do not have a variable called other you have called it collision

languid spire
tough plinth
#

I wrote what he said 🥲

languid spire
#

try using your brain

tough plinth
#

That's the same thing as if you said to a lawyer to launch a spaceship

languid spire
#

no it's not.
you were given some example code, it's up to you to make it work with your situation, that is the nature of writing software

tough plinth
#

Uh. So, in the script they provided, that variable is being accepted by the system, but in my situation, for some reason not.

tough plinth
languid spire
#

notice how they have a Collider (because they are using a trigger) and you have Collision

#

2 different objects, 2 different requirements.
Go read the Collision docs and see how to get to an object which will accept a CompareTag method

tough plinth
#

Does it work only with Collider?

languid spire
#

hint. Collider is a Component. Collision is not, so you need to get a component reference from the collision

tough plinth
#

Alright, I will search the docs, tyy

tough plinth
#

Well, I fixed everything and it works perfectly, so.. Is that CompareTag thing was so that important? Like OnCollisionEnter works good itself, all you need is to just play sound?

#

And no need to see if it was a player or block, it will collide with everything.

lucid oriole
#

hey, I've started learning unity few days ago, (have some background as c# dev) rn during making the 2d game, I'm on really early stage (like player character movement + attack with few animations), and even now I'm getting feeling like my code is starting to be spaghetti, do you have any tips how to keep code clear/some guidelines/done projects that i should refer to when designing code structure?

untold plank
#

How do I regenerate the #C project/solution files ( Unity 6, 6000.0.32f1, LTS ) ?

swift crag
#

The example code uses CompareTag to decide if we just collided with something with a tag of "Player"

#

If you don't care what you collided with, then I suppose checking its tag is no longer relevant

cloud matrix
swift crag
#

have you checked what you're actually hitting with the raycast?

cloud matrix
#

yeah it prints 'ladder'

#

umm i mightve found the problem but dk how to fix

swift crag
#

line 26 in that method is a closing curly brace

#

so I don't think the code you sent matches the code you're running

cloud matrix
#
prompt.enabled = true;```
#

thats line 26

#

i did update the code but it didnt work

void Update()
{
    RaycastHit hit;
    Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range);

    if (hit.transform.CompareTag("Ladder"))
    {
        Debug.Log(hit.transform.name);
        prompt.enabled = true;
    }
    else
    {
        prompt.enabled = false;
    }
}```
#

could it be bc theyre prefabs (its a multiplayer game)

swift crag
#

Click on the error in the console once while the game is running

#

This will highlight the object in the hierarchy

#

Perhaps you have multiple "Raycast Testing" components in your scene

#

(or perhaps the reference is missing from the one that actually exists)

cloud matrix
spiral narwhal
#

How do I program a fade in for UI text? Like using fill amount for images basically - I've tried incrementing the maxVisibleCharacters steadily, but it's not quite the effect I want

swift crag
cloud matrix
#

oh

swift crag
#

hence the error coming from that line

cloud matrix
#

alr ill undo and check rn

#

brb

#

nvm i gtg its 2am for me

charred heart
#

Hi, I'm trying to create a computer screen in my game. My problem is I can't click the icon (in world space). Didn't know what settings I messed up.

polar acorn
charred heart
swift crag
#

ah, you don't get much information out of it when using the new input system

#

(i have no idea why)

#

I don't think you can easily get this information out of the EventSystem directly, either

#

it has IsPointerOverGameObject, but that doesn't tell you what it's over

charred heart
#

Maybe some UI are sitting in front of those icons. I created another button in the world space, and this btn works fine.