#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 46 of 1

slender nymph
#

that's called code lens. and it makes it helpful to determine where/when things are being used. why would you want to disable useful debugging tools?

unreal phoenix
#

I don't, I just remeber a time when they were off to the right and not spacing out the text

slender nymph
#

are you certain you aren't thinking of something else? because code lens has looked like that for years

#

or maybe you're just remembering a time when you didn't have it due to vs code not being properly configured

unreal phoenix
#

It just spaces out the text a lot vertically and drives me a bit crazy

#

I mean I don't see it's superior over hitting [shift+F12]

azure zenith
#

Can you declare two prefabs?

fossil drum
swift crag
#

Although, that's partially because VSCode gives the lens an entire line, iirc

#

rather than a cute half line

keen dew
#

Same, I just find it annoying. How many times something is referenced isn't really the kind of information that needs to be visible all the time.

swift crag
#

i mostly just care about whether it's used at all

simple sun
swift crag
#

That would search the current file for things with the same name.

simple sun
#

well, for entire project, its ctrl+shift+f

#

isnt that the same?

swift crag
#

Text search is still very different.

#

Text search just looks for matching text.

simple sun
#

well you can apply filters to it to make sure

swift crag
#

References are based on code analysis.

simple sun
swift crag
#

So it doesn't matter if I have the word "Hit" all over the place in my code

simple sun
#

thats built in to vs right? not a unity thing

swift crag
#

This will only show me things that refer to this specific identifier

#

It's in your IDE, yes

#

so VSCode/Visual Studio/Rider/etc.

simple sun
#

great, might show this in my class

swift crag
#

Text search usually works fine within a single file, but short/common names will cause lots of problems

swift crag
mystic oxide
#

thanks took me quite a while, its work fine now

wooden socket
#

i want a prefab to start in front of the player and then disappear when thrown. how would i achieve this

#

the game is about throwing darts

#

(3D)

cosmic dagger
wooden socket
#

would that be in an void update?

cosmic dagger
#

you place it in your code where you need the dart to appear . . .

wooden socket
#

can i just show u my code lol

subtle hedge
simple sun
subtle hedge
#
    private void Update()
    {
        Ray ray = new Ray(transform.position + (Vector3.up * .5f), Vector3.down);
        if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
        {
            footPlacement = hit.point + (Vector3.up * heightOffset);
        }

        transform.position = footPlacement;
    }``` i even tyed to do this way'
simple sun
#

can you print out what is being hit

subtle hedge
simple sun
#

is that the only output you get if you move it around?

simple sun
#

ok now do the same but with the offset

subtle hedge
#

without the offset the leg moves how is supposed to but the height isn't, and there is no collider hit appearantly

#

i removed the height offset also from the ray

simple sun
#

so there is different things being hit depending if you use offset or not?

subtle hedge
#
  Ray ray = new Ray(transform.position, Vector3.down);
  if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
  {
      footPlacement = hit.point;
      Debug.Log(hit.collider.name);
  }

  transform.position = footPlacement;```
subtle hedge
#

but with this code it debugs that it hit the ground

#

the ground is always hit, there are no other colliders in front of the ray and foot is contolled by one script

simple sun
subtle hedge
#

only the ground is hit

#

my exact problem is that the foot dosen't maintain the position when moved forward or left and right and backwards when adding an offset to it

#

it moves up and down tho

queen adder
#

can anyone help me with Building my game? i get errors

#

This is wierd

#

i never had build issues

simple sun
simple sun
silk night
upper crypt
#

I've been struggling so long with it. I've made a 3d game on unity but the player (sphere) moves (wasd) the opposite direction of what it's supposed to be (w goes back, a goes right), I've tried everything
I suspect that maybe I've created the game in the opposite direction of the camera, but I still rotated the camera by 180, and it didnt work, the player too.
here's the code


// Include the namespace required to use Unity UI and Input System
using UnityEngine.InputSystem;
using TMPro;

public class PlayerController : MonoBehaviour {
    
    // Create public variables for player speed, and for the Text UI game objects
    public float speed;
    public TextMeshProUGUI countText;
    public GameObject winTextObject;
    
    private float movementX;
    private float movementY;

    private Rigidbody rb;
    private int count;
    private bool isGrounded;

    // At the start of the game..
    void Start ()
    {
        Debug.Log("Player position: " + transform.position);
        // Assign the Rigidbody component to our private rb variable
        rb = GetComponent<Rigidbody>();

        // Set the count to zero 
        count = 0;

        SetCountText ();

                // Set the text property of the Win Text UI to an empty string, making the 'You Win' (game over message) blank
                winTextObject.SetActive(false);
    }

    void FixedUpdate ()
    {
    

        // Create a Vector3 variable, and assign X and Z to feature the horizontal and vertical float variables above
        Vector3 movement = new Vector3 (movementX, 0.0f, movementY);

        rb.AddForce (movement * speed);
    }

    void OnTriggerEnter(Collider other) 
    {
        // ..and if the GameObject you intersect has the tag 'Pick Up' assigned to it..
        if (other.gameObject.CompareTag ("PickUp"))
        {
            other.gameObject.SetActive (false);

            // Add one to the score variable 'count'
            count = count + 1;

            // Run the 'SetCountText()' function (see below)
            SetCountText ();
        }
    }

        void OnMove(InputValue value)
        {
            Vector2 v = value.Get<Vector2>();

            movementX = v.x;
            movementY = v.y;
        }

        void SetCountText()
    {
        countText.text = "Count: " + count.ToString();

        if (count >= 12) 
        {
                    // Set the text value of your 'winText'
                    winTextObject.SetActive(true);
        }
    }
}```
eternal falconBOT
silk night
queen adder
#

a little bigger image

silk night
queen adder
#

here

silk night
#

Does any of the errors have any explanation text?

upper crypt
#

oh my god

#

it's been 2 days and you saved me

#

you're a god, thanks!!!!

queen adder
#

OK ALL of them have wierd texts

north kiln
queen adder
#

here is my bui;d setting btw

subtle hedge
eager elm
queen adder
simple sun
queen adder
#

What else do i need?

upper crypt
#

How can I change that code of mine, in a way that if the player touches an object, it loses points? (It can only earn points for now)

silk night
eager elm
#

*Is my guess

subtle hedge
simple sun
upper crypt
simple sun
upper crypt
#

thank you, I know of it from our lesson i'm just not sure how to work with it, i'll experiment a bit

north kiln
queen adder
#

i need to submit this project tommorow to school

queen adder
#

here is the burst stuff you said

simple sun
subtle hedge
queen adder
north kiln
queen adder
north kiln
#

using the visual studio installer

silk night
#

or add module via hub

queen adder
#

what to do now?

silk night
#

Click on modify on 2022

queen adder
#

i used 2019 to make all scripts

silk night
#

Then tick "Universal Windows Platform development" & "C++ Universial Windows platform support for vNNN build toold (ARM64)" + all the others that your error discribes

#

It just needs to be installed

#

to have the sdk available

#

doesnt matter which one you use in the end

queen adder
silk night
#

Hmm oh wait, your compiler tries to use 2019 if i see that right, well then you might have to modify 2019

silk night
#

In the error you posted are 4 packages you need to install

#

at the top should be a tab where you can look for individual components

#

use the search bar in there

upper crypt
#
// - instantiates an explosion Prefab when hitting a surface
// - then destroys itself

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    public Transform explosionPrefab;

    void OnCollisionEnter(Collision collision)
    {
        ContactPoint contact = collision.contacts[0];
        Quaternion rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
        Vector3 position = contact.point;
        Instantiate(explosionPrefab, position, rotation);
        Destroy(gameObject);
    }
}``` this for example, do I replace "gameobject" with the name of the object I want it (the player) to be collided with? I'm not good with coding..
silk night
#

the term gameObject in any MonoBehaviour returns the gameobject your script is on

fossil drum
upper crypt
upper crypt
polar acorn
upper crypt
#

I want the player to have a point removed when it collides with an enemy/grenade

#

but I don't know what to write

pseudo sable
summer stump
# upper crypt

This says you wrote the name in PlayerController. But the code above is ExampleClass..

#

Did you declare it in PlayerController, or only ExampleClass

polar acorn
upper crypt
#

ok so I wrote this cs void OnCollisionEnter(Collision collision) { ContactPoint contact = collision.contacts[0]; Quaternion rotation = Quaternion.FromToRotation(Vector3.up, contact.normal); Vector3 position = contact.point; Instantiate(explosionPrefab, position, rotation); Destroy(gameObject); } in playercontroller

#

sorry for any confusion

pseudo sable
#

did you also add the public Transform explosionPrefab;?

upper crypt
#

no

pseudo sable
#

that's your problem then

#

Instantiate(explosionPrefab, position, rotation); <- on this line it doesn't know what explosionPrefab is because you've not defined it

upper crypt
#

youre right it worked fine now

#

do i add box collider on the enemy?

#

because the player goes through it now

pseudo sable
#

whatever has this script will need a collider yeah

#

otherwise OnCollisionEnter will never happen

upper crypt
#

when i add a box collider

#

my enemy instantly dies?

#

idk how

pseudo sable
#

if you have a floor or something with a collider then that will be triggering that method too

queen adder
#

Hello

My AI doesnt go to the target. I use SetDestination that returns a bool -> True if set successfully and false if isnt. I get a returned value "true", but my AI doesnt go to the Set Destination. I'd like some help here

pseudo sable
# upper crypt idk how

you'll need to interrogate the collision and find out where it came from, the easiest way probably is to add a tag to your projectile (or whatever it is) and check for that, if it has the right tag then do the explosion/destroy logic

#

otherwise just ignore the collision since it'll be a floor/wall/etc

pseudo sable
queen adder
# young warren Can't help without code
IEnumerator SummonGhostRoutine(){

        //Make art material Emission
        //art_material.SetColor("_EMISSION", Color.red);
        //Play sound for art
        art_audio.Play();
        //Make art particles play ONCE
        particle.Play();

        //Play Ghost Animation (DONE)
        animator.Play("GhostAnimation");
        yield return new WaitForSeconds(8);

        //Set a barrier so player WONT get in spawn 
        barrier1.SetActive(true);
        barrier2.SetActive(true);

        //Ghost speed = 0
        agent.speed = 0;

        //Ghost set target
        if(agent.SetDestination(player.position)){

            Debug.Log("true!");

        } else {

            Debug.Log("Fault");

        }
        Debug.Log("!");
        yield return new WaitForSeconds(5);
        //Ghost speed = NORMAL SPEED
        agent.speed = 5;
        Debug.Log("!1");
        
        //Start timer
        TimerStarted = true;

    }
pseudo sable
upper crypt
#

and also, what do I do after I tag it? I don't assume "tagging" will magically work on its own

pseudo sable
#

then check if that == "Projectile" or whatever you name the tag

modest rapids
#
for (int i = 0; i < 2; i++)
        {
            Vector3 tmpPosition = transform.position;

            switch (i)
            {
                case 0:
                    tmpPosition.y = tmpPosition.y + offset;
                    break;
                case 1:
                    tmpPosition.y = tmpPosition.y - offset;
                    break;
            }
            RaycastHit2D[] hit = Physics2D.RaycastAll(tmpPosition, rb.velocity.normalized, distanceFront, mask);
            Debug.DrawRay(tmpPosition, rb.velocity.normalized * distanceFront, Color.red, 0.2f, false);
(slightly more code below)

#

is there a better way to code this instead of a switch?

upper crypt
#

sorry im really bad

pseudo sable
#

oh sorry, inside the OnCollisionEnter method, the Collision collision parameter that gets passed in is details about the collision, collision.gameObject is the other gameobject that's involved in the collision (not the gameobject that the OnCollisionEnter method is on

modest rapids
#

gameobject.tag = tag from the gameobject this script is on

#

collision.gameobject.tag is the tag from the object that was collided with

upper crypt
#

collision.gameObject.tag

pseudo sable
#

collision.gameObject.tag inside that method will be the tag that you're colliding with, that's the hint! what did you name your projectile tag?

fringe pollen
# queen adder could anybody pls-

Are there any errors? Have you baked a nav mesh? Is your target within the nav mesh bounds? Does your AI have a path they could take to get there meaning that the path isn't blocked or the AI isn't isolated from the target?

queen adder
#

Ima try smth rn

pseudo sable
#

so you can check for if the tag is enemy, and then do whatever you like, or more likely if its not enemy, do nothing

upper crypt
#

like this?

#

sorry

pseudo sable
#

okay so probably worth understanding what exactly that example code is doing, going line by line:

  1. fetch the contact point of the collision
  2. fetch the rotation opposite to the contact point (i think, i'm rubbish at rotations)
  3. fetch the position in space of the collision contact
  4. create an instance of an explosion prefab at the position and rotation from above
  5. destroy this gameobject
    the question is, when do you want this set of instructions to happen? on every collision, or only on collisions with the enemy?
polar acorn
#

Turn off collapse if it is on

pseudo sable
# upper crypt

to sum up those 5 lines i described, it makes an explosion at the collision point and deletes this gameobject

upper crypt
#

I just want, whenever the player touches the enemy, the player's points get reduced by 1 each time

#

but I don't tknow how to do that 😭 I don't understand the collision examples i find online

pseudo sable
#

yep! will get to that but it's important to understand the code that you have just now rather than getting ahead

#

if you understand what you have it's easier to understand what needs to change

pseudo sable
#

so at the moment, when the player touches any collider, it will create the explosion prefab and delete itself right?

#

be that a floor, wall, etc

upper crypt
#

well, that's not what I want

#

but currently, when I start the game, the enemy instantly dies

#

somehow

pseudo sable
#

i know but i'm saying that's what's happening right now with the code you have

polar acorn
pseudo sable
#

so the next step towards your goal of "take a point away when the enemy touches the player", is to adapt your code so that the explosion/delete effect only happens when an enemy touches you

#

then after that, we can change the explosion/delete to be "remove a point"

#

so, going back to what i was saying before, inside your OnCollisionEnter method, the collision variable lets you see the tag of whatever gameobject touched you, accessible through collision.gameObject.tag - you want it so that your code in OnCollisionEnter only runs if the other tag is "Enemy"

#

var otherTag = collision.gameObject.tag; could be the first line in your method, to poke in the right direction

upper crypt
#

code works but the enemy dies instantly without doing anything

pseudo sable
#

there's more to write, but it's worth trying to figure it out, essential programming skill!

upper crypt
#

how do I log it?

pseudo sable
#

Debug.Log("some string") is the method for logging

polar acorn
upper crypt
#

i think i got it

rich adder
upper crypt
#

ide?

rich adder
#

VS

upper crypt
#

visual studio?

polar acorn
#

Are your errors underlined in red

pseudo sable
#

okay so you can do a Debug.Log(collision.gameObject.tag) in your OnCollisionEnter method to print the tag of the other gameobject (spoiler, it will probably be an empty string if it's the floor and it doesn't have a tag)

upper crypt
#

I only have this now

rich adder
#

you have to check inside the VS when you write something incorrect does it underline it red ?

upper crypt
#

this for example?

#

cuz in VS it says no issues found

rich adder
#

right this should show in VS

upper crypt
pseudo sable
#

they're wondering if you look at that line in VS, is there a red underline on it?

#

at the end of the line

polar acorn
eternal falconBOT
polar acorn
#

So it shows errors as you make them

cosmic vigil
#

is it needed to do that config even if all is running good? or is it just if your ide is not working proper with it, a bit confused now

polar acorn
#

If not, then do it

upper crypt
#

what do i even download from the site? it's all so confusing...

cosmic vigil
#

i see ill go check now quick quick

upper crypt
#

I use 2022 vs

polar acorn
queen adder
#

@polar acorn Late but, here

IEnumerator SummonGhostRoutine(){

        //Make art material Emission
        //art_material.SetColor("_EMISSION", Color.red);
        //Play sound for art
        art_audio.Play();
        //Make art particles play ONCE
        particle.Play();

        //Play Ghost Animation (DONE)
        animator.Play("GhostAnimation");
        yield return new WaitForSeconds(8);
        animator.StopPlayback();

        //Set a barrier so player WONT get in spawn 
        barrier1.SetActive(true);
        barrier2.SetActive(true);

        //Ghost speed = 0
        agent.speed = 0;

        //Ghost set target
        if(agent.SetDestination(player.position)){

            Debug.Log("Target Set");

        } else {

            Debug.Log("Target set Fail");

        }

        Debug.Log("!");
        yield return new WaitForSeconds(5);
        //Ghost speed = NORMAL SPEED
        agent.speed = 5;
        Debug.Log("!1");
        
        //Start timer
        TimerStarted = true;

    }

I have an animation playing before setting a target

polar acorn
upper crypt
#

the code won't open now...

cosmic vigil
#

looks like your file isnt open

#

to me atleast

polar acorn
upper crypt
cosmic vigil
upper crypt
cosmic vigil
#

poor lad got 3 mentions in a row

upper crypt
#

sorry

#

I open the script from unity and it won't show up now

rich adder
#

regen project files in External Tools after

upper crypt
#

why is everything going wrong with me

#

I click "OK" but the window opens again, without stopping

rich adder
# upper crypt

we have no way of determining what you did and didnt do by this screenshot alone..

upper crypt
#

ill try to follow the website again, brb

polar acorn
#

Okay, but each of those logs you put in that code are each only run one time right?

#

You don't have multiple coroutines stacking?

#

Then I would first try to fix that Animation Event error you're getting. An error could be preventing your code from executing. It's unlikely but might as well eliminate it as a possibility

#

Either remove that animator event or assign it a function

upper crypt
#

ok I added the "game dev with unity" option, but I don't know how to setup the ide

#

!ide

eternal falconBOT
polar acorn
#

Can you show the full !code for the function with this coroutine on it?

eternal falconBOT
polar acorn
#

Sometimes all you gotta do is ask the question and the answer reveals itself

queen adder
#

YOOOO

#

I Exported the game

#

YES!!

upper crypt
#

there is "wintext" how can i write more than 1 "wintext"? is there like, an endtext/losetext?

#

I want to have a text show up when the player loses

#
{
    countText.text = "Count: " + count.ToString();

    if (count >= 12) 
    {
                // Set the text value of your 'winText'
                winTextObject.SetActive(true);
    }
    if (count < 0)
    {
     
        winTextObject.SetActive(false);
    }
``` something like this
wintry quarry
#

you can write the code to do anything

#

you could also just use a single text object and change what it says

royal osprey
#

guys, how to make a camera movement like swipe left/right with bounds?

upper crypt
#

i just dont understand

#

how can I add the option of a "losetext"?

polar acorn
#

If you want more text objects, make more

#

That's not a built in Unity thing

upper crypt
#

I changed the code a bit but i don't see "losetext" being created 😦

polar acorn
#

Show where you created it

upper crypt
#

Ok I did it! I just didn't make the public line

#

Now it shows up šŸ˜„

wintry quarry
#

well actually I guess if you're just calling SetActive GameObject is fine

#

but WinText is a TMP_Text

upper crypt
#

I just tested it, it works

wintry quarry
#

probably best to keep them consistent

calm osprey
#

anyone familiar with InputManager? I was able to make it so when I press WASD my character moves and changes to the running animation, but I also need a transition into the idle animation when I stop moving.
I already have a condition set, I just don't know how can I code "if I press nothing, do this".

rich adder
#

nah fr you gotta show the code

buoyant knot
#

InputSystem is worth learning. Even if learning it absolutely sucks

polar acorn
rich adder
buoyant knot
#

idk. I thought it’s just called Input

polar acorn
rich adder
#

oh idk I thought it was Inputclass/Inputmanager vs InputSystem

#

ah ok

calm osprey
#

in Unity it's called InputManager

polar acorn
#

InputManager is the old system, accessed via the Input static class

upper crypt
#

how to make it so the game restarts after 2 seconds, and NOT instantly?

rich adder
#

love the names Unity uses

buoyant knot
#

or async

rich adder
#

Task.Delay barely works in unity

buoyant knot
#

Coroutines are good for waiting for specific parts of a frame of Unity’s calculations.
Async works outside unity, and lets you return values

#

That’s the tldr

polar acorn
rich adder
#

yeah async is a double edge sword

atomic bison
#

hi guys!

polar acorn
#

It's like a zombie virus

atomic bison
#

with unity inapp 4.9.3 we are safe?

#

im using Version 4.9.3 - June 14, 2023 of inapp purchasing from unity

rich adder
#

whats that? is this coding related?

atomic bison
rich adder
#

this isn't a specific coding question

polar acorn
buoyant knot
#

in general, once you start with coroutine/async, it is hard to switch

#

and a lot of unity devs had issues migrating out to other engines because they were used to Coroutines

rich adder
#

Im glad unity has entry points to async /IEnumerator

#

private async void Start() | private IEnumerator Start()

upper crypt
#

Last assistance please

#

When the player falls in a hole, the game restarts

#

but when I tried to make it so when the player's points go below 0, it doesn't restart

rich adder
#

this alone isn't helpful

upper crypt
#

what more should I give? the code?

rich adder
#

thats a start

upper crypt
#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ReloadScene : MonoBehaviour
{
    void OnTriggerEnter(Collider col)
    {
        if (col.CompareTag("Player"))
        {
          
            Invoke("RestartScene", 2.0f);
        }
    }

    void RestartScene()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
``` this is for when the player falls down
#

it restarts after 2 seconds

#

I tried to do this for when the player's points go below 0 ```cs void SetCountText()
{
countText.text = "Count: " + count.ToString();

    if (count >= 12) 
    {
                winTextObject.SetActive(true);
    }
    if (count < 0)
        loseTextObject.SetActive(true);
        Invoke("RestartScene", 2.0f);

}```

fossil harness
#

Are coroutines only ideal for things tied to the frame rate like animations?

summer stump
#

Good for lots of things

fossil harness
#

Can you run them on the FixedUpdate cycle? I was looking over the execution order and saw they fall under Update so I wasn't sure

summer stump
#

FixedUpdate is a whole different cadence

slender nymph
rich adder
#

also where is SetCountText even called at

fossil harness
upper crypt
#

it's working now thanks

ashen ferry
#

is it possible to declare some kind of method in class and in its constructor take in implementation of it as a parameter lol

#

like if I declared Action type and I could pass in Action but I want to keep implementation inside class

slender nymph
#

wdym by "keep implementation inside class"

ashen ferry
#

idk how to explain kekW

#

like legit change how that method behaves ig

slender nymph
#

i genuinely do not understand what it is you are trying to achieve. the only way to pass methods around is with delegates like Action

pseudo sable
#

yeah what's the problem you're trying to solve?

ashen ferry
#

I need 4 instances of class with method which does in each of them almost exact same thing

#

but like math stuff I cant make base implementation then override in child and add onto it or something

slender nymph
eternal needle
ashen ferry
#

I imagined this like append this code to this method

#

kinda thing

pseudo sable
#

why do you need the 4 instances that do slightly different things, probably going to need an example because it really smells like @slender nymph s link

eternal needle
#

Instead of obfuscating what you're trying to do by showing fake examples, just show what youre doing with the real problem

#

Because right now it just sounds like you need a delegate and that's all

pseudo sable
#

as far as keeping the implementation of the extra action in the class, you could define the actions you want inside the class, and have the callers use them like instance.SomeMethod(instance.ExtraAction1)

azure zenith
#

Help:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
slender nymph
#

Your script should either check if it is null or you should not destroy the object.

pseudo sable
#

what is your code?

azure zenith
#

I am trying to instantiate another prefab but it will not because of the error

ashen ferry
#

Yea thats what I wanted I didnt thought I can set actions like this lol ty

rich adder
slender nymph
charred spoke
#

My bet is he referenced a scene object and not the prefab from the project tab

charred spoke
#

You owe me a coke

azure zenith
#

Come here, lol

#

I actually have some

charred spoke
#

I will come when you least expect me

dry tendon
#

heey, does anyone knows how could i do this image to have the same size in all screens?

slender nymph
dry tendon
#

ok, sorry, then i post the question there

slender nymph
#

or you could just look at the pins in that channel and learn how to do it

dry tendon
#

i couldn't find the solution

high epoch
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public float moveSpeed = 5f;
    puplic transform movePoint;
    // Start is called before the first frame update
    void Start()
    {
        movePoint.parent = null;
    }

    // Update is called once per frame
    void Update()
    {
        if(Math.Abs(Input.GetAxisRaw("Horizontal")) == -1f)
        (
            movePoint.position += new Vector3(Input.GetAxisRaw("Horizontal"), Of, Of);
        )

        if(Math.Abs(Input.GetAxisRaw("Vertical")) == -1f)
        (
            movePoint.position += new Vector3(Of, Input.GetAxisRaw("Vertical"), Of);
        )
    }
}

This is my script and here is the errors

pseudo sable
#

you're using ( instead of {

#

for your ifs

slender nymph
#

do you see red underlines in your code?

high epoch
#

no

languid spire
#

'puplic'

slender nymph
# high epoch no

then you didn't follow all of the instructions for configuring your !IDE like you claimed you had earlier

eternal falconBOT
pseudo sable
#

you should set up your ide and it would warn you that there's multiple problems with your syntax

#

puplic, using brackets instead of braces

languid spire
#

lowercase t in transform

high epoch
#

im in the docs but im now sure where to go

pseudo sable
#

IDE configuration that boxfriend linked

high epoch
#

thats where i am

slender nymph
#

then follow the instructions

high epoch
#

ik they are confusing

slender nymph
#

what are you confused about

high epoch
#

idk where to put the editing revolved thing

slender nymph
#

the Editing Evolved section just lists the features you will have when vs code has been configured. it's not a "thing" you "put" anywhere

high epoch
#

oh

#

then what do i have to do

slender nymph
#

follow all of the instructions above that

high epoch
#

i did that

slender nymph
#

then regenerate project files and restart vs code

slender nymph
#

it's like you didn't even bother reading what it said

high epoch
#

what does that mean

summer stump
high epoch
#

bet

summer stump
#

Sometimes when you get the extensions, the PATH is not updated until restarted

#

Otherwise you don't have the SDK and need to get it, but try the restart first

slender nymph
#

or they missed getting the extension entirely

sour wren
#

Guys, i wanna center my wheel as the same center of my car, how i can solve this?

#

Like, reseting the Pivot for the center of the wheel

wintry quarry
rocky canyon
#

u can use empty containers.. and adjust the model as a child to represent where u want the pivot.. and then use the parent's pivot (center)... or you can pull the models into blender or some other 3d software to adjust the pivot urself

quiet dune
#

Hi, strage behavior with NavMeshAgent.destination: I have a Vector3 "destination", where x = 512.0001, that i assign to a NavMeshAgent.destination, but the destination than reads a Vector3 where x = 512 without the .0001. Afterwards, when checking navMeshAgent.destination == destination, it returns false. I want to check at a later time, whether navMeshAgent.destination equals the destination i (might have) set earlier, but this behavior screws that up. Any ideas on that?

languid spire
summer stump
#

Check if the distance is below a threshold

buoyant knot
#

== and floats are bad juju, unless you use == 0f to check for having assigned a zero, and not having changed it at all

quiet dune
#

Ahh yes, i read that before. Thanks for the advice! I'll try using Approximately

buoyant knot
#

i find unity makes float == work somehow, but it’s still pretty bad

#

Q: Is there a light way to sort (usually very small) subsets of lists?

#

eg, I have a list of size 20, and just need to sort the elements in slots 0-3

sour wren
rocky canyon
#

u have to Apply the transform

#

and then re-export it as a fbx, obj or w/e

#

if u did it correctly it'll show the new pivot when u swap into Pivot mode as someone already posted

#

changing that to Pivot

buoyant knot
#

When you get multiple hits from a Cast, is it sorted by distance?

rocky canyon
#

i think, in order of what it hits first

#

not 100% on that though

buoyant knot
#

one more cast-related question: If i cast and hit something multiple times, do I just get the first result?

#

example

languid spire
buoyant knot
languid spire
quiet dune
#

If a project is halted by a break point, is there a way to prevent the unity editor from locking up?

orchid trout
#

I moved some monobehaviour .cs code around through the project window and now suddenly none of the moved code is able to find types and namespaces that it had no issue with before moving it - why is this the case, how do I fix it and prevent it from happening again?

#

none of it was editor code and I didnt move it out of the project or out of assets yet somehow it cant find the rest of the code and this has never happened to me before

azure zenith
#

I am creating a game where you splat fruits. I would like to display a splat effect when you splat the fruits, how would I do this? I have the splat prefab

orchid trout
#

visua; studio can't even find the code that is being referenced when I search the entire proj for it, but its not been removed from the proj I even have the other files OPEN in visual studio

polar acorn
# orchid trout I moved some monobehaviour .cs code around through the project window and now su...

It is likely that one or both of them have changed Assemblies. If your project uses Assembly Definitions, each one contains only its own folder and any child folders, with each file belonging to only one assembly. You can set references in the inspector for one assembly definition to reference the other. In this case, whatever assembly definition this script belongs to needs to reference whichever one UIProto_ReceiveInputs belongs to

#

Also, if Unity doesn't have any issues with these and it's purely in your IDE, consider regenerating project files so it knows the new locations of those files

unique willow
#

I'm trying to make a very basic script that sends you to another scene when the enemy collides with the player but for some reason it's not working. Are there any noticable issues?

orchid trout
polar acorn
orchid trout
#

code team confirms Assembly Definitions are in use

polar acorn
unique willow
#

That's how they move in other scripts

summer stump
polar acorn
unique willow
#

yes

summer stump
#

With the exact same capitalization

unique willow
#

Wait I think I figured it out

#

Typically it spits an error when I forget to add it to the build settings

#

So I figured I already did

orchid trout
unique willow
#

Ok now it works

polar acorn
#

(or the other way around, this script moved into a different assembly definition that does not have a reference to the one UIProto_ReceiveInputs belongs to)

buoyant knot
#

which is not acceptable.

swift crag
swift crag
buoyant knot
#

maybe that’s why I thought it would work

swift crag
#

I check for float equality when I am using something like MoveTowards

#

It will reach an exact value.

quiet dune
#

@buoyant knot @swift crag I mean just to be able to select game objects, to see their stats, where they are, their gizmos etc. Not having the "game" run or change anything

azure zenith
#

I am unable to see my debug.log messages

slender nymph
#

that doesn't sound like a code issue. but you have probably hidden them in your console

azure zenith
#

I am sure the function works so I don't know why the message won't display in the console

slender nymph
#

you have probably hidden them in your console

azure zenith
#

If you want to display effects after you slice a fruit, you would instantiate it, right?

zealous oxide
#

hey friends. in one of my gameobjects scripts i'm trying to instantiate a prefab but the script doesnt seem to find said gameobject/class(?) [despite the desired script having the same name verbatim]. i've tried to drag the script/gameobject prefab into the inspector of the script & game object doing the instantiating but it doesnt let me drop it in. the wierd thing is that i've managed to make this work on 3 other objects/scripts but i cant remember how

slender nymph
#

I do not see a KingsForkProjectile component

zealous oxide
slender nymph
#

or was that other prefab not the object you were trying to drag into the first object?

slender nymph
zealous oxide
#

the crescent dart controller prefab was an example where i did manage to get this working

slender nymph
#

okay so show the object you are trying to drag in

summer stump
zealous oxide
azure zenith
#

This is so weird

#

I have a class and my game works without it

#

Like wth

polar acorn
#

I mean, if you're not using it, then it doesn't matter if it exists or not

azure zenith
#

I need to use it

polar acorn
#

Maybe you should actually elaborate on the issue instead of posting in vague terms

azure zenith
#

I want my debug.log statements to show in my console but it will not

#

So the class is not working

polar acorn
#

Show code

silent obsidian
#

I've been working a little bit on refactoring the code for my player. I'm trying to get the health management logic outside the player class and onto a class of it's own.

I feel like I am doing something really wrong here.

Can anyone point if that's how composition should be achieved?

public class HealthManager : MonoBehaviour
{
    public void SetHealthToMaxHealth(int currentHealth, int maxHealth) {
        currentHealth = maxHealth;
    }
    
    public void ReceiveDamage(int damage, int currentHealth, int armour){
        if (armour != 0 ) {
            damage -= armour;
        }

        if (currentHealth - damage < 0) {
            currentHealth = 0;
        } else {
            currentHealth -= damage;
        }
    }

    public static void DamageObject(Collider other, int damage) {
        DestroyableObject obj = other.gameObject.GetComponent<DestroyableObject>();
        obj.ReceiveDamage(damage);
    }
}
polar acorn
summer stump
short hazel
#

Their new values will be discarded when execution exits the methods

silent obsidian
#

That's what I was trying to ask exactly but my english won't help me, how should the logic for systems such as this be handled?

vocal glacier
#

Does anyone know why I can't drag muliple audio game objects from the Hierarchy window to the Project windown in Unity 2018.1.9f2? I am trying to create prefabs of audio to put in assets bundles for VAM. All the documentation for Unity says I should just be able to drag muliple GameObjects into the Project window from the scene and it will make a prefab for each object. I get a red circle with a slash that indicates this action is not allowed. I can only drag one object at a time.

silent obsidian
#

My intuition tells me that i should somehow pass a reference

short hazel
# silent obsidian My intuition tells me that i should somehow pass a reference

Example of the faulty system:

void A()
{
    int health = 100;
    Damage(health, 10);
    Debug.Log(health); // -> 100, because when passed to 'Damage', a copy of the value is made.
}

void Damage(int health, int damage)
{
    health -= damage; // edits a copy of the variable
}

You need to have the current health and armor as class variables instead, to fully separate them from the other scripts

#

It's possible to pass-by-reference, but for a fully composition based model, the variables related to health must be offloaded to the health script

silent obsidian
#

@short hazel How could I offload variables in a manner that would allow the HealthManager script to be reusable?

I think doing something like GameObject.find("Player").GetComponent<Player>().health is not the right answer.

short hazel
#

You'd have a Player script and a Health script aside on the same object

#

Then Player could serialize a variable of type Health, so you can drag-drop the health script onto the player script, in the Inspector

silent obsidian
#
public class Player : MonoBehaviour
{
    [Header("Combat Stats")]
    [SerializeField] private int currentHealth;
    [SerializeField] private int maxHealth = 100;
    [SerializeField] private int armour = 33;
    [SerializeField] private int damage = 25;
    [SerializeField] private HealthManager healthManager;

    void Start() {
        healthManager.SetHealthToMaxHealth(currentHealth, maxHealth);
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.F)) {
            HealthManager.ReceiveDamage(55, currentHealth, armour);
        }
    }

So it should look something like this?

buoyant knot
#

is the most lightweight way to implement BFS a queue?

silent obsidian
#

oh actually it does not make sense because I would still be passing a value.

short hazel
#

And the armor if it makes sense

silent obsidian
#

But what if I would want to reuse the HealthManager for an enemy (that has different values. E.g: maxHealth = 200)

short hazel
#

Then you go in the enemy's inspector and change the value to 200

#

It's a separate script instance compared to the one on the player, which will stay at 100

silent obsidian
#

Ohhh right because it's a serialize field. Okey, I finally understand it.

#

Thank you a lot!

short hazel
#

The 100 you set in code is the default value that will be set when you attach the script for the first time. Once you modify it in the Inspector, it's not used anymore

#

Inspector takes precedence over values set in the code (for field initializers like you have here)

silent obsidian
#

Wait, actually can you reference a script through a SerializeField? or the only way is through getComponent<>()

polar acorn
silent obsidian
#

I think it only allows me to point to the object HealthBar

polar acorn
silent obsidian
#

it does

polar acorn
#

Then you are referencing the HealthBarScript

silent obsidian
#

oh, thanks

fossil harness
last grove
#

how would I set the players orientation equal to the slope they are standing on while still keeping them going in the same direction? transform.up = slopeInfo.normal + new Vector3(0, playerCam.eulerAngles.y, 0);This is what I have right now and it resets the player to the axis of whatever part they're standing on

fossil harness
last grove
#

is it possible to get the y value of a rotation for 1 frame and not have it update after?

eternal needle
last grove
eternal needle
dawn sparrow
#

What's the easiest way to check if any particular bounding box is in a cameras view frustum, with no regard for efficiency?

silent obsidian
#

I'm trying to learn the new input system, is there a significant difference between messages / events?

buoyant knot
#

an event is a delegate. When the delegate gets invoked by myDelegate?.Invoke();, any function added to the delegate gets called

#

think of a delegate like a list of functions. You add/remove functions from this list, to change what gets called when .Invoke is called

#

make sense?

#

example:
public event Action OnJumpButton;

I can add:
OnJumpButton += Jump;
OnJumpButton += SelectMenuItem;
OnJumpButton += MakeJumpSound;
….
OnJumpButton -= Jump;
OnJumpButton += Swim;

#

delegates are fast because you are giving the delegate all the deets of what to call before it needs to get called. Messages need to sift through to go find targets. Delegates don’t have the searching bs

#

Actions are delegates, btw

#

event makes it so you can only +=, -=, and .Invoke it

silent obsidian
#

Are there any specific factors to be taken into account when choosing for which behavior to go for? As I've read through the documentation and also your explanation I have a feeling that the events system might be a better fit for more robust games.

buoyant knot
#

it is

#

I only use messages when Unity forces me to, because of OnCollisionEnter/Exit

#

also, when you ctrl+R to find all references (to find everything activated by a specific message), good luck. That shit doesn’t work because it’s just a bunch of different functions that just happen to have the same name in different classes

#

with delegates, you are calling += etc on that one variable. So Ctrl+R to find all references directly takes you to all the different scripts that are getting triggered

#

i cannot stress enough how huge that feature is

dawn sparrow
buoyant knot
#

InputSystem is a more complex use case because you are also playing with parsing InputActionCallbackContext objects

#

but the core of delegates is simple

silent obsidian
#

Do you happen to know of any good resources that covers how to implement the new input system w/ events?

buoyant knot
#

i learned from youtube. and it was painful

#

there are many tutorials tho

#

I recommend you try out basic event delegates first

summer stump
#

It's quite similar to that

#

You just get a CallbackContext instead of something you explicitly pass.

#

And the Context is a struct with values

buoyant knot
#

General workflow:
using System;
In Class1:
public event Action<int> OnEvenNumber;

int i = 0;
void Update() {
i++;
if (i %2 == 0) // if i is even
OnEvenNumber?.Invoke(i);

}

static cedar
#

What are events? UnityChanThink
I've been using delegates and never really quite understood events.

#

The docs just say you subscribe and then stuff.

buoyant knot
#

Class2:

void PrintMe(int i) { Debug.Log(i);}
void Start() {
GetComponent<Class1>().OnEvenNumber += PrintMe;
}

#

those two classes together will, every frame, increment a number in Class1, if it is even, it invokes delegate, Class2’s PrintMe method gets called on that input, and it prints that number

#

Action (no <T>) just takes no arguments

#

understand?

buoyant knot
silent obsidian
#

I kinda get it, they should hire you to write the docs imo

outer coral
#

Is there a simple way to wait for a UI button onClick event to trigger in a coroutine? E.G.

private IEnumerator doStuff(){
//do stuff
yield return new WaitUntil(/*Wait for the ui button press onClick to fire*/);
//do more stuff
}

I looked online, couldn't find much. Help is appreciated thanks!

Really would rather not keep a bool that gets turned true when the button is pressed... seems inefficient and messy

buoyant knot
silent obsidian
#

Thank you!

static cedar
#

Essentially.

buoyant knot
#

event allows fewer things than normal delegate

#

a normal delegate lets you fuck with the list of methods in multiple ways

#

events force that to not happen

#

so you don’t need to worry about one random class totally fucking up the delegate

static cedar
#

mydelegate val1 = null;
myevent val2 = null; //not allowed.

#

Ok. UnityChanThink

buoyant knot
#

if you have only been doing +=, -=, and Invoke(), then it would be interchangeable

#

event is a modifier

#

you can have public Action myAction1; and also public event Action myAction2;

#

it’s like a public/private access modifier almost. applying the event keyword blocks several things from being allowed

#

but it’s only blocking because you are telling it to block it, and not because it can’t do it.

static cedar
#

Why the hell did the docs go through saying it's a subscription thing and didn't really mention the differences between a event and a normal one that much? UnityChanSleepy

buoyant knot
#

+= is called subscription

#

-= is unsubscription

#

you (un)subscribe functions to the delegate

static cedar
#

Those are terms I'm more acquainted with JS and AS. UnityChanAFK

#

But yeah ok.

buoyant knot
#

delegates just have a lot of terms and shit that make them harder to learn

polar acorn
buoyant knot
#

there are events, actions, delegates, functions, lambdas, subscription, and unsubscription. And some of these are similar, but slightly different

teal viper
#

Actions and Funcs are just types of delegates. Events are a programming pattern.

static cedar
#

One more question, are delegates considered a collection? UnityChanThink

#

Ok chat stopped. UnityChanPanicWork

teal viper
#

They do have some kind of linked list internally though

buoyant knot
#

they don’t count as a collection, but they function as a collection where you have zero access to the contents

#

you can’t know how many, you can’t do any sort of indexing. You can’t even guarantee any sort of sorting (that’s not in the spec)

#

they are a collection in the abstract sense where they function as a container of functions

#

but you don’t get things like .Contains, delegate.Count, delegate[5], delegate.Sort, deegate.Concatenate…. none of that is a thing.

eternal needle
buoyant knot
#

as far as we understand, the critical thing is that ordering within a delegate is not a part of the spec

#

so if you need A to happen before B, and both are in the same delegate, you can’t actually enforce that order

eternal needle
#

i would go with the bool you said was "inefficient and messy". Its a bool, it is neither inefficient or messy.
A string based search for IsInvoking is DEFINITELY messy

static cedar
#

How does the == operator work?

buoyant knot
#

it does whatever it is defined to do

#

it needs to be implemented on a class-by-class basis

cosmic dagger
buoyant knot
#

they feel like a collection of functions, without actually being a collection

outer coral
#

^i'm not using the parameterized method

#
yield return new WaitUntil(() => myButton.IsInvoking());
eternal needle
cosmic dagger
static cedar
cosmic dagger
#

The methods are invoked in the order they were added . . .

buoyant knot
#

you’re confusing her

#

basic vanilla delegate is like a bucket of functions. You throw functions into the bucket (or pull them out), and call them all at once

#

they technically have an order, but order isn’t a part of the language specification, so that COULD change at any time

swift crag
#

you should not depend on the order, yes

buoyant knot
#

they keep an internal collection, but that is an implementation detail that you do not get access to

#

it’s like a black box. you don’t get to look inside

twin bolt
#

I want to make a elevator that will move up to a set position, Should i use Animation or .movetowards, to prevent issues with the player following the elevator, or the camera bugging?

buoyant knot
#

MovePosition and MoveTowards

swift crag
#

the important question is: how does the player move?

buoyant knot
#

elevator should probably have a kinematic rigidbody

twin bolt
buoyant knot
#

is player dynamic or kinematic rb

swift crag
#

A kinematic rigidbody elevator ought to be able to push the player correctly, then

#

Assuming the player is not kinematic.

#

Make sure that you're only moving the elevator via the rigidbody

twin bolt
buoyant knot
#

making objects ride other objects can be hard as shit depending on the scenario

swift crag
buoyant knot
#

MoveTowards is a vector operation

swift crag
#

all that MoveTowards does is produce a value between two points

buoyant knot
#

MoveTowards just helps you calculate a vector position. By itself, MoveTowards doesn’t actually move anything

swift crag
#

it does not intrinsically do anything

twin bolt
#

Should i just go the route of faking the elevator moving, using a courotine?

swift crag
#

if you use rb.MovePosition(pos), where pos was calculated via MoveTowards, that sounds fine

twin bolt
#

ok

swift crag
#

Especially since the elevator is kinematic

buoyant knot
#

yeah. just move it

#

kinematic RBs go to target position without asking questions

swift crag
#

you certainly wouldn't want to physically simulate how an elevator works lol

twin bolt
swift crag
#

ah

#

that is also reasonable

#

Also a convenient place to put scene loads, if your scenes are big enough to require a load time

buoyant knot
#

i would only recommend that for a Luigi’s Mansion 3 elevator, where it is actually just a loading zone between levels

twin bolt
#

I'll just do that to resolve any issues, i might run into.

hoary citrus
buoyant knot
#

elevators are an inside job

twin bolt
hoary citrus
buoyant knot
#

no he wasn’t

twin bolt
buoyant knot
#

Alex Jones told me so

#

he also explained to me the benefits of his amazing ā€œManJuiceā€ true energy supplements, with real bits of man in every bite

swift crag
buoyant knot
#

the annoying part is when we have to rebuild the whole country when you get on a plane

#

gotta keep the round earth myth going

twin bolt
#

What if everything behind you, doesnt exist, until you look?

buoyant knot
#

that’s a real thing

twin bolt
#

What if somebody that your playing online multiplayer(in real life) with is, looking at things you arent looking at. Does that mean that what they are seeing doesnt exist to you, or does your system, have to work harder to render everything?

hoary citrus
teal viper
twin bolt
#

i mean in real life though?

static cedar
#

Why are we considering real life?

twin bolt
hoary citrus
swift crag
#

this is just solipsism in a trenchcoat

teal viper
teal viper
# twin bolt Yea

Probably the wrong place to ask these questions then. And I don't think anyone knows the answer anyway.

hoary citrus
#

Is it developed in Unity? Does reality pay runtime fees?

twin bolt
#

Does a blind person, live lag-free, since nothing is actually being rendered, its just a whole bunch of audiosources?

teal viper
hoary citrus
#

"God doesn't pay runtime fees" - Albert Einstein

swift crag
#

we should probably steer back to something on-topic

north kiln
#

What on earth does this have to do with code or Unity

static cedar
twin bolt
#

Ok i'm done

static cedar
#

Seems legit.

nimble marlin
#

Wait, Unity uses Box2D for 2D physics?

teal viper
#

Yep

pseudo frigate
#
public void OnPointerClick(PointerEventData eventData)
{
    Vector2 localCursor = new Vector2(0, 0);

    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RawImage>().rectTransform, eventData.pressPosition, eventData.pressEventCamera, out localCursor))
    {
        Texture tex = GetComponent<RawImage>().texture;
        Rect r = GetComponent<RawImage>().rectTransform.rect;

        //Using the size of the texture and the local cursor, clamp the X,Y coords between 0 and width - height of texture
        float coordX = Mathf.Clamp(0, (((localCursor.x - r.x) * tex.width) / r.width), tex.width);
        float coordY = Mathf.Clamp(0, (((localCursor.y - r.y) * tex.height) / r.height), tex.height);

        //Convert coordX and coordY to % (0.0-1.0) with respect to texture width and height
        float recalcX = coordX / tex.width;
        float recalcY = coordY / tex.height;

        localCursor = new Vector2(recalcX, recalcY);

        CastMiniMapRayToWorld(localCursor);
    }
}

private void CastMiniMapRayToWorld(Vector2 localCursor)
{
    Ray miniMapRay = GameManager.Instance.minimapCam.ScreenPointToRay(new Vector2(localCursor.x * GameManager.Instance.minimapCam.pixelWidth, localCursor.y * GameManager.Instance.minimapCam.pixelHeight));

    RaycastHit miniMapHit;

    if (Physics.Raycast(miniMapRay, out miniMapHit, Mathf.Infinity))
    {
        //Debug.Log("miniMapHit: " + miniMapHit.collider.gameObject);
        GameManager.Instance.cam.transform.position = new Vector3(miniMapHit.collider.gameObject.transform.position.x, GameManager.Instance.cam.transform.position.y, miniMapHit.collider.gameObject.transform.position.z-4);
    }
}

im using this code with OnPointerClick so that when i click my minimap it's repositioning the player's camera. it works as i want it to but id like to make it so that when im holding the mouse button down over the minimap i could drag around and move the camera that way too.

#

what's the best way to go about doing that?

inner marsh
#
    {
        if (Input.GetAxis("Vertical") > 0)
        {
        myT.position += myT.forward * movementSpeed * Time.deltaTime * Input.GetAxis("Vertical");
        }
        if (Input.GetAxis("Vertical") < 0)
        {
        myT.position += myT.forward * movementSpeed * Time.deltaTime * Input.GetAxis("Vertical") * 0.5;
        }    ``` so im making a thrust thing obv and when you go backwards its slower but the game doesnt like me putting * 0.5, any idea why?
charred spoke
#

0.5f

inner marsh
#

alr ty

pseudo frigate
timber tide
#

OnDrag has a few different interfaces

pseudo frigate
#

i included drag start and end, but not sure if anything needs to be in them

timber tide
#

One thing to note is that only one event is triggered per frame

#

OnDragStart is a single event, but I think you can pretty much use onpointerclick too for it?

#

Not everything needs to be used, but OnDrag is pretty much the main event which should contain the repositional logic.

#

Ah, actually OnDragStart doesn't trigger until you hold down the mouse and move a bit

pseudo frigate
#
private PointerEventData _pointerData = null;

private void Update()
{
    if (_pointerData != null)
    {
        OnPointerClick(_pointerData);
    }
}

public void OnPointerDown(PointerEventData eventData)
{
    _pointerData = eventData;
}

public void OnPointerUp(PointerEventData eventData)
{
    _pointerData = null;
}

i tried this too but this doesnt work, curious how come that is

timber tide
#
        Texture tex = GetComponent<RawImage>().texture;
        Rect r = GetComponent<RawImage>().rectTransform.rect;

This would be set at OnStartDrag probably

#

And then OnEndDrag you can probably ignore or unset everything being used

nimble marlin
#

Is it worth it trying to build a nice platformer player controller using RigidBody2D?

timber tide
#

If you want to use unity's physics system you go with rigidbody2D

#

otherwise you're implementing logic like gravity and stuff

nimble marlin
#

Yep, I am trying to build a nice player controller rn, but my player feels like he is falling through viscous liquid, increasing mass hinders movement on the x-axis, increasing gravity also has some similar affect.

summer stump
nimble marlin
summer stump
#

What are you setting the Y value to?

#

You could also do AddForce if you'd rather btw,
Which is also Rigidbody based movement.

nimble marlin
summer stump
nimble marlin
#

speed...

summer stump
#

Maybe show the code?
That is wild

Wait... are you multiplying it by deltaTime?

#

Because you should not be

nimble marlin
nimble marlin
summer stump
#

Ok yeah... get rid of deltaTime

#

You'll have to reduce the speed a lot

#

And then, you are also setting the y value to 0 sometimes actually

nimble marlin
#

player just became Flash

summer stump
#

GetAxisRaw will return 0 when you aren't giving input. And 0 times your speed is obviously 0. So you are repeatedly setting velocity to 0 when in the air, which explains the "viscous fluid" feeling

#

You should do a ground check, and when not on the ground, set the velocity to a gravity value like -9.8

nimble marlin
summer stump
#

But if you were using transform.position += someValue, you would want to scale that with deltaTime

#

Basically, unity does the work for you with AddForce and velocity haha

nimble marlin
summer stump
nimble marlin
cosmic dagger
#

yes, you can . . .

nimble marlin
cosmic dagger
#

not that i recall. you need to determine how you're going to move: set velocity, add force, or the Move methods (kinematic rigidbody). each have their pros and cons. i'd look up videos, controllers, or references on those first . . .

nimble marlin
#

righty

high epoch
#

hey how can i get autocorrect is vs code

gaunt ice
#

!ide

eternal falconBOT
high epoch
solemn fractal
#

Hey guys, Created this here to control my ship animation.. it is working but the prob is that if I click to fast right and left sometimes it doesnt register and the animation doesnt happen.. anyway to fix that?

keen dew
#

Don't set Turn_Right false when you release left button and vice versa

solemn fractal
#

will try it thank you

solemn fractal
keen dew
#

šŸ‘ and don't cross-post in the future

inner marsh
#

[RequireComponent (typeof(RigidBody))] what did i do wrong?

keen dew
#

You spelled Rigidbody wrong

high epoch
young warren
north kiln
eternal falconBOT
sullen rock
#

is it possible to add a baked lightning map to an object I am instantiating?
(or instantiate them with the map already)

gusty lagoon
#

Hey guys. Does anybody here know how to call a function from a script from another script without using tags?

ruby python
#

@gusty lagoon is the object containing the 'target' script dynamically created or always in the scene?

burnt vapor
high epoch
#

i made mistsakes but idk where

tiny terrace
#

Is it okay to have 2 canvas assigned in 1 camera?

timber tide
#

Yeah, having multiple canvas is pretty standard.

neon ivy
#

trying to use Physics.SphereCastAll but in the editor it's telling me my starting pos needs to be a ray and in the documentation they have a whole bunch of parameters I have no idea what to do with. namely Direction. anyone know how to use this?

teal viper
delicate portal
#

Hey I'm currently working on a house building system. How can I make sure that the buildable object will only be placed when its not clipped into the wall? And any solutions for the buildable incline issue while the cursor is on the wall?

neon ivy
copper pumice
teal viper
neon ivy
#

it should be one of these

copper pumice
#

And make the layers not interact then.

delicate portal
#

Sure so if the wall touch the buildable, it shopuldnt be placed?

teal viper
neon ivy
#

direction

delicate portal
copper pumice
teal viper
neon ivy
#

like, no idea what direction it wants. why does it even need a direction

#

do I just say vector3.left?

teal viper
copper pumice
#

And then make it so that the collider for checking only interacts with the correct objects.

neon ivy
#

no idea xD

delicate portal
neon ivy
#

I don't care about the direction

teal viper
#

If you have no idea, then why even do the cast?

neon ivy
#

I just need to get all objects in the sphere

silent obsidian
#

Hello guys. How can I get the same behaviour as in "GetAxis("Horizontal")" with the new input system?

I don't want it to jump instantly from 0 to 1 and -1 but rather to go smoothly.

copper pumice
teal viper
copper pumice
#

And then something like: if (isTouchingWall) return;

neon ivy
#

ah

timber tide
teal viper
#

Sphere cast is like rolling a ball in a direction.

neon ivy
#

oooh

neon ivy
#

that explains why I was confused. thanks

#

I thought a spherecast was just a spherical raycast

silent obsidian
#

@copper pumice I want to recreate the behaviour that "GetAxis" has but with the use of the new input system.

timber tide
#

it's more related to the standard raycast while overlap sphere is for a general area

queen adder
#

Today I found out that there was actually a hack for this. Just click on any object in the heirarchy, then spam Alt+Left arrow

delicate portal
teal viper
delicate portal
neon ivy
#

so I'm not fully understanding casts in general UnityChanThink

queen adder
#

also check if the code even work without the if check

teal viper
queen adder
#

actually idk if getmask will work too

neon ivy
#

so it's just a raycast with thickness?

teal viper
#

With a radius, yes.

neon ivy
#

UnityChanClever knowledge has been obtained, thanks

copper pumice
#

And I actually meant to change it so that the layers only interact with each other in settings, not with an if statement. But that should probably work too. Check the layer spelling and make sure that the correct objects has the layer enabled. You can always try tags instead.

delicate portal
copper pumice
#

Hmm alright

#

Well if it works it works.

copper pumice
#

You can change it so that only certain layers collide with other layers in the physics settings

delicate portal
#

I know that

solid yew
#

Hey, I'm trying to set a single component of an object's rotation without changing the other components. I don't want to change the rotation incrementally (i.e. with RotateAround), I want to directly set the value.

I've been trying this:

    void SetRotation(float angle)
    {
        transform.localRotation = Quaternion.Euler(angle, transform.localEulerAngles.y, transform.localEulerAngles.z);
    }```
but I'm getting some strange behaviour when `angle` is greater than 90 degrees (the angle flickers between being greater than 90 and less than 90). I've read that reading from `transform.localEulerAngles` is a bad idea, but I haven't been able to find an alternative solution. Does anyone have a better way to do this?
frosty hound
queen adder
frosty hound
#

Maybe it's just shift and no alt. Im not here to test it. I use it all the time but it's second nature that it's just muscle memory.

north kiln
#

Iirc it's just alt, not shift at all

queen adder
#

actually, the alt or shift isnt even important

#

holding left arrow can do it alone

frosty hound
#

It is now because I'm confused and need to know what I've been doing. But that's hours away from checking. Lol

queen adder
#

yea, left arrow can do it alone, alt speeds it up

dusk minnow
#

Is there a way to tracj which objects are enabled and disabled in a parent and save this?

lone sable
#

Anyone have any resources they could point me twoards, to editing a sprite shape via runtime? I know I could grab each spline point, and have a handle the player could move, however, adding new points is I'm not sure?

teal viper
dusk minnow
queen adder
#

How can I fix this error. WARNING:We recommend using a newer Android Gradle plugin to use compileSdk = 33

keen dew
#

It's a warning, not an error

queen adder
#

No it's an error.

keen dew
#

No, it's a warning. Those errors are caused by something else. Post the full error message to #šŸ“±ā”ƒmobile

fringe pollen
#

Just to make sure, if I for example do otherScript.someArray = this.someArray; and then do this.someArray[0] = 7;, then otherScript.someArray[0] == 7; right?

slender nymph
#

yes, arrays are reference types. so if both variables reference the same array instance then modifying the elements of one of those variables will affect the array referenced in both variables.
however you cannot assign a new array instance to one variable and expect the other to be affected

swift crag
#

Assigning to a variable will only affect another variable if your variable is a ref

#

well, or out, I guess

forest wolf
swift crag
#

as you mentioned

forest wolf
#

However alternative way, which I use more often is not working directly with euler angles but rather setting the transform.foward to the right direction. Basically you find a direction to the target by doing (targetPosition - originPosition).normalized and then set it to e.g. transform.forward

swift crag
#

Yeah. That can often behave better.

somber wren
#

hello guys ! hello can i force a moving gameObject to stay at a certain distance of the ground ?

fossil drum
somber wren
#

without physics* sorry

#

like i have a 3d object that can climb on walls (its a spider)

#

but i want it to stay always at the same distance of its ground

buoyant knot
#

is it dynamic or kinematic?

somber wren
#

kinematic i guess ?

#

it has no rb no collider

buoyant knot
#

uh… it has no collision at all?

somber wren
#

yes

#

only with raycasts and all

buoyant knot
#

ok, then you’re going to need to raycast or spherecast to move around

somber wren
#

its already moving and climbing walls

buoyant knot
#

it would maybe be easier to give it a kinematic rigidbody and set its layer to ignore raycasts

somber wren
#

i just want it to stay a certain height of the ground

#

i could put a collider without a rb tho idk, my professor doesnt want physics in the project

buoyant knot
#

that way nothing can interact with it, but the physics system can smoothly move it from point a to point B

somber wren
#

its already moving hello u read what i write 😭😭

#

its already moving and climbing walls
i just want it to stay a certain height of the ground
i could put a collider without a rb tho idk, my professor doesnt want physics in the project

To sum it up

buoyant knot
#

what I mean is if it has a Kinematic RB, you can tell it to MovePosition once per physics frame

#

and the physics system will figure out where to put it in between for every frame

#

makes sense?

somber wren
#

it does

#

but doesnt solve anything, ive already been through that

#

gravity fucks up the whole thing

buoyant knot
#

gravity has no effect on kinematic RBs

somber wren
#

if i put gravity, it cant work, if i remove it, it doesnt work too

#

oh yeah

#

kinematics one mb

#

but a rb would just make my spider fly

buoyant knot
#

does the spider climb walls?

somber wren
#

loup

#

im gonna throw my computer off my window

buoyant knot
#

like vertical walls

#

or just like slopes

#

and ceilings

somber wren
#

it walks on everything

forest wolf
somber wren
#

for the 4th time,

buoyant knot
somber wren
buoyant knot
#

he needs to initialize to a certain snapping direction

forest wolf
somber wren
#

bc it wouldnt move

buoyant knot
#

then spherecast to look around

#

yeah, I think the pieces all make sense now

#

so what is the part you have trouble with?

forest wolf
somber wren
#

wait

#

im gonna picture you bc

buoyant knot
#

when you say it can walk walls but not maintain distance, you mean you can’t get it to keep distance, but it does respect level geometry shape?

#

or that it does not respect level geometry shape, so if you have a hill, it moves along a plane?

somber wren
#

here my spider climbing a cube

#

and going down on the other side

#

he is my problem, wrong distance of the ground

buoyant knot
#

oh it’s a tetrapod

#

ok, so right now you use a cast to know where it needs to go, right?

somber wren
#

yes its the red rays

buoyant knot
#

that cast outputs a RayCastHit, which has a normal for the surface

somber wren
#

yes

#

and then pouf spider.normal = hit.normal

#

with a lerp, and more of a rotation but yeah

buoyant knot
#

if you need to translate normal to the surface, then just transform.translate by hit.normal * the distance you need

forest wolf
#

I think I still struggle a little bit to understand the issue. Do you want to keep the body certain distance from the surface it is walking on or never be able to reach the ground (the blue surface)?

buoyant knot
#

i dont understand which part is confusing

#

that’s a good question

#

because that would be an inverse kinematics problem

forest wolf
#

Can you sent also 2 pictures: one of what is going on (the problem) and the other (in the editor, not in the play mode) how you would like it to look like?

somber wren
#

body certain distance from surface

#

maybe its just a translate to do

#

thats why im in code beginner xd

buoyant knot
#

oh shit that is hard

#

given that it is a tetrapod

forest wolf
#

In that case I believe the simplest way would be to do as you say simple translate. You could simply do transform.position = targetPosition + (transform.up * distance)

buoyant knot
#

actually maybe not so hard, if you solve the body first

#

not hard if you are okay with it looking janky lol

buoyant knot
somber wren
#

whats hard

buoyant knot
#

yeah, this is a hard problem if you want it to be accurate

#

because it isn’t a simple object

#

it’s a tetrapod

somber wren
#

it is

buoyant knot
#

the four legs move with the body

somber wren
#

the legs follow the body, i just need to touch to the body

#

the controller moves my body and the legs follow by themselves, procedurally animated

buoyant knot
#

so if you want it to be accurate, you need to solve the motion of the whole thing like a robot

somber wren
#

i've that rn

#

i just want it

#

to be at a the right distance of the surface its walking on, thats all

buoyant knot
#

making the body level is easy

#

that is the super easy part

somber wren
#

then i just need that

buoyant knot
#

making the legs match up to accurately move everything in a way that makes sense is the hard part

somber wren
#

ITS ALREADY DONE 😭

buoyant knot
#

so yeah, just use some spherecasts, bro