#💻┃code-beginner

1 messages · Page 132 of 1

queen adder
#

Wether or not ur calling the Move() Method

quick edge
#

That's strange

#

Generally what do people use for final projects? Rigidbody or CharacterController?

queen adder
#

I prefer CharacterControllers

#

But it depends on ur game

quick edge
#

Souls like

queen adder
#

I would say character controller because im guessing your player is just gonna have basic movement and a jump

#

Rigidbodies are physics based stuff like reacting to explosions, forces, stuff like that

#

But u can achieve the same stuff with a rigidbody

quick edge
queen adder
#

Try it, like i said it always seem to detect collisions whether or not i use Move()

#

Dont be afraid of anything test it and see

#

You eventually come up with ur own conclusions on which system is better

quick edge
#

Let's say I'm calling Move on every frame. Then I'm always calling Move so there is necessary collisions right ?

queen adder
#

Si^

quick edge
#

Perfect then. Thanks!

ivory bobcat
#

Else if you aren't moving, you could always opt to set damaged flags and evaluate damage relative to those rather than when colliding.

quick edge
#

Can you expand on this please? I've never heard of that

ivory bobcat
#

When you've hit the object and are required to receive damage per second/frame/whatnot, you'd set a flag and poll the damage to be done elsewhere.

quick edge
#

What is a flag ? I don't find anything about it

ivory bobcat
#

A bool.

queen adder
#

Not literally a flag

quick edge
quick edge
queen adder
#

haha no brother lol

unborn wasp
quick edge
queen adder
#

The charaterController has a collider on it at all times

#

You seem to think that it only has a collider when u call Move()

quick edge
#

Oh okay. I tought it was an alternative to the thing we talked about. My bad

queen adder
#

Thats not the case

ivory bobcat
quick edge
#

Yes sorry, I thought it was an alternative

#

Thanks for the help!

wintry quarry
wintry quarry
ivory bobcat
# unborn wasp

What should happen if no monster sprites are found? Why is it failing to load monster data? Look into the errors.

wild dagger
#

Yo can someone help me out? I have no idea how to fix this

#

it just says no valid target

#

when im tryna use my tilemap and I feel really stupid

ivory bobcat
#

Is this related to coding?

wild dagger
#

where's a more appropriate chat to put it

#

I just figured since its a beginner chat might be ok to put it here

#

its not related to coding, more just using this and I've never had this issue before when using tilemaps

ivory bobcat
#

Probably #💻┃unity-talk
Make sure to tell people how you're getting the error (where are you seeing the error and what are you trying to do ie how they would reproduce it)

boreal tangle
#

!code

eternal falconBOT
unborn wasp
#

i rly dont know how repair this...

cobalt creek
#

so i created a custom namespace and am trying to access it; which one should i use preferably? I think they all work

libnsClass comp = gameObject.AddComponent<libnsClass>();
var comp = GetComponent<libns.libnsClass>();    
var comp = GetComponent<libnsClass>();
nimble scaffold
#

Well guys I really need a quick help.... My mum is asking me what will the world do with game development

#

Pls answer

short hazel
gaunt ice
short hazel
#

By "clearly apparent" I mean something like var x = new Thing();

nimble scaffold
cobalt creek
gaunt ice
#

you dont need to type the namespace if there is no ambitious
eg you want to use System.Random and UnityEngine.Random at the same time then you must type the namespace, but using UnityEngine alone then not necessary

#

though you may need a using XX=namespace.XX since just typing XX may cause ambitious to compiler (again there is random class under system and unityengine), but we usually use the one under unityengine

graceful citrus
#

what is this?

wintry quarry
graceful citrus
#

it only has a cube and a movement script

gaunt ice
#

then i think you can just clear the console and ignore it?

graceful citrus
#

but its worrying

#

also all my scripts have blue plus icons in the corner

wintry quarry
wintry quarry
graceful citrus
#

why would it automatically download?

desert elm
#

hm, random question before I try to code this-
could I have a script that, for each transform in a list
renders a raycast to that transform, but if that raycast collides with a collider/gameobject with a specific tag, it will assign a variable to the coordinates where it collided, creating a point, and measure the distance between that point and its starting position, adding the amount to a different variable
then.
then, it would render another raycast betweeen the point where it collided and the transform in the list, up until it collides with something different, reaches that transform, or reaches the edge of the collider with that specific tag. In the case of the latter two, it would either assign the coordinates to a third variable, creating a second point, or use the transform as the second point. It would then measure the distance between the first and second point, multiply it, and then add to variable we added the distance before

wintry quarry
gaunt ice
#

Debug.DrawRay

desert elm
gaunt ice
#

or DrawLine since you may have start and end point already

graceful citrus
#

i don't know where the collab packege is im very confused

wintry quarry
open kernel
#

Hi, for some reason the door doesnt play the open animation, can someone help?```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerActions : MonoBehaviour
{
public Transform cam;
public float playerActivateDistance;
bool active = false;
private void Update(){
RaycastHit hit;
active = Physics.Raycast(cam.position, cam.TransformDirection(Vector3.forward), out hit, playerActivateDistance);
if(Input.GetKeyDown(KeyCode.E) && active == true){

        if(hit.transform.GetComponent<Animator>() != null){
            hit.transform.GetComponent<Animator>().SetTrigger("Activate");
        }
    }
}

}

wintry quarry
graceful citrus
wintry quarry
#

Version Control software

#

Like Git

graceful citrus
#

i still have blue pluses

desert elm
graceful citrus
#

and i still have the red warning about collab service

gaunt ice
#

you already comes up with the step, try to translate them to code first

wintry quarry
desert elm
#

it is yes

#

I found out how to code that behaviour later

#

just, differently

wintry quarry
#

Everything is possible

#

There are no limits other than hardware limits and your skill

graceful citrus
#

why is it still here

#

whats happening to me

#

im terrified

#

its a curse

#

why is it following me

#

im making a new project and if it follows me ill hurt someone

short hazel
#

What?

#

The plus icon? Pretty sure it means that was added since your last Plastic SCM commit

graceful citrus
unborn wasp
short hazel
#

It might be erroring because you don't have the package

graceful citrus
#

i deleted the project, im remaking it now. thats why i didn't post the error just now

#

i did before, and that was then

#

it was a project with nothing but a cube and a movement script

hidden sleet
#

got another strange issue with items existing but also not existing. It says that DisplayInventory itself does not exist, but if it's attached to the object like this how is that possible?

#

this is that thing again where I pick up an item and this should then change ui elements of an inventory display, but it beats me as to why it says it doesn't exist at all

queen adder
#

The error says whatever refernce you had to it got destroyed

#

Is there any part of ur code that is destroying the instance of DisplayInventory?

hidden sleet
#

nothing aside from switching the scenes unloading the gameobject as it should

queen adder
#

Does any of ur code persist from scene to scene

hidden sleet
#

as it's just a script attached to the object

queen adder
#

Share a screenshot of the entire Inspector

hidden sleet
#

none of the code should, only thing I assume would are my scriptable objects because they hold my inventoy

queen adder
#

Share code

hidden sleet
dim stream
#

hi, one little question, if i want a sound when an enemy die where i have to put all the things because i have the audio source on the enemy and i put it in the script of the enemy but the sound dont reproduce

swift crag
#

so the audio source is being destroyed?

dim stream
#

look

swift crag
#

one option is to just use the static method AudioSource.PlayClipAtPoint

dim stream
swift crag
#

It creates an audio source for you and destroys it when it's done

dark hatch
graceful citrus
#

is there a specific shader that should be applied to a material for minimal performance cost? is unlit texture the best available? is there any less performance costing?

summer stump
# dim stream

This destroys the object in the same frame you create it.
An alternative to what Fen said is to use the second parameter of Destroy to delay it

dark hatch
swift crag
#

an unlit shader is relatively cheap, yes, but this seems like an odd question to ask

graceful citrus
#

with minimal performance cost

#

i want it to be able to run on a samsung fridge

swift crag
#

Choose the shader that produces the visuals you want

#

You shouldn’t just do things “because optimization”

graceful citrus
#

but my idea is "if its the most optimal, its probably the shittest"

#

and i want it the shittest

graceful citrus
swift crag
#

I do not understand

summer stump
swift crag
#

If you want a visual style, ask about creating that visual style

graceful citrus
#

i want the material shader that can run on a toaster best

#

the most optimal

teal gulch
swift crag
languid spire
#

shaders do not run on toasters

graceful citrus
swift crag
#

That requires effort

river roost
dark hatch
river roost
#

you can set the texture's max size so you dont have to scale them down manually

graceful citrus
#

is point filter the most optimal filtering?

summer stump
#

Grab the render profiler and test things

river roost
graceful citrus
summer stump
graceful citrus
#

i thought you were supposed to just do it here

summer stump
#

Do what there? Set the graphics settings? You are supposed to do it there

graceful citrus
supple citrus
#

I just want to spawn an instance at my mouse, any help

wintry quarry
supple citrus
dark hatch
wintry quarry
#

Where is that code? Is it ever running?

summer stump
supple citrus
languid spire
#

AI Code?

supple citrus
#

no lol

dark hatch
#

comments feel a bit too perfect lol

supple citrus
#

its for a school project they have to be

#

extra marks :v

dark hatch
#

also, getmousebuttondown and getmousebuttonup do not run in same frame

short hazel
#

Most likely AI. There were in another server, starting out

dark hatch
#

so you are not actually setting the position before instantiating -> NaN

short hazel
#

Or it's copy-pasted

supple citrus
#

cuh its not Ai

dark hatch
#

retrack mouseposition in input.mouseButtonUp()

supple citrus
#

it was working before with the Mouse Inputs as they are, I dont remember changing anything

#

wym by retrack?

dark hatch
misty obsidian
#

How to make smaller this white rectangle hitbox?

short hazel
#

Default value for a vector is (0, 0, 0) not (NaN, NaN, NaN) so it's the mouse position that has a problem

dark hatch
#

just put the first red mark, before the second red mark in Input.getmousebuttonup()

supple citrus
#

But I want the Object to spawn where you click, not release

#

So I need to set initialmousepos when MouseButtonDown is triggered, no?

dark hatch
#

something might be resetting InitialmousePos then

#

Debug.Log(Intialmousepos) everywhere in update, to see where it goes NaN

#

you'll trace it quite easily if initialmousePos isn't changed anywhere

supple citrus
#

Oh its not the issue that i thought it was

#

InitialMousePos isnt nan at all

dark hatch
#

oh, seeing the error: you are doing "transform.position = ..." of the instantiated object somewhere then.

short hazel
#

If you click on the error you'll get an extended description telling you where in the code it occured

#

Do that

dark hatch
#

click on the error, where does it say it originates from

#

it should be in blue colour, the topmost file name you see

supple citrus
#

From fixedupdate here

#

These are the two spaces where transform.position is used

dark hatch
supple citrus
#

yes

dark hatch
#

check if velocity is nan with debug.log

short hazel
#

Post the error it's way easier than guessing

#

It contains the file, and the line number directly

supple citrus
#

It is the velocity

#

Bottom Line

short hazel
#

Divided by zero at some point

dark hatch
supple citrus
#

it is

short hazel
#

You get NaN when you divide by zero, if I remember correctly

dark hatch
#

probably some awkward calculation condition being fulfilled leading to a /0

supple citrus
#

This calculates how far you drag back

#

and then the planets velocity is set to it

#

But I dont know where it would divide by zero

dark hatch
#

did you debug.log velocity ?

supple citrus
#

yes its NAN

#

After the first click it becomes nan

dark hatch
#

just keep moving debug.log statement further back till you see it's not Nan, error identified

short hazel
#

This is the only line where you divide. Either the r^2 is 0, or Scale is 0

supple citrus
#

And the distance def isnt zero

swift crag
#

that doesn't do what you think it does

short hazel
#

Yeah that isn't doing what you think it does

swift crag
#

10^5 is...

#

[counts on fingers]

supple citrus
#

The error said its located on transform.position += velocity

#

Oh whats happening

swift crag
#

1010b ^ 0101b = 1111b = 15

#

that's the binary XOR operator

dark hatch
#

yeah.. code is pain sometimes.. use mathf.pow

#

only reason it's there

supple citrus
#

Oh so I have to use math pow again

swift crag
#

I don't think there's an integer power operator

supple citrus
#

But wouldnt that still not be zero?

swift crag
#

But you can just use Mathf.Pow

swift crag
#

just look at the values yourself

dark hatch
supple citrus
#

uff okay

#

So the debugger

deep quarry
#

Yo,
This is my simple Script for my CameraMovement, which follows the player.

public class CameraMovement : MonoBehaviour
{
    // Player
    public Transform target;

    public Vector3 offset;

    void Update() {
        transform.position = target.position + offset;    
    }
}

However, I would like the camera to stay behind the player even when the player is rotating (along the y-axis).
Any idea of how to do this? I suppose I need to use Transform.forward of the player (target)?

supple citrus
#

Should i not do MouseClick.initialv ?

#

I originally had a getcomponent

short hazel
# supple citrus

You have still a lot of XOR operations for Mass and G, keep in mind to fix those once the problem is fixed

supple citrus
#

Does pow work for negative exponents

short hazel
#

But yes you can construct numbers like 10e-11f to avoid some Mathf.Pow calls

#

I'd check DistanceToObject.magnitude to see if it's not 0

unborn wasp
#

Would anyone be willing to help me modify this script so that it randomly selects different monsters on a different scene from another folder? I would greatly appreciate your assistance.
https://hatebin.com/asnmzskzsb

supple citrus
#

fml whys that happened

#

That would mean sunposition and planet position are the same

short hazel
#

The two positions you used to construct the vector are identical

eternal needle
supple citrus
#

Why would they be identical..

short hazel
#

If the script is on the sun, OR if you dragged yourself onto Suni in the Inspector

supple citrus
#

I named it Suni just so i could tell them apart

#

The script is on planet

#

so it must be sunposition thats messed up

short hazel
#

And why are you multiplying the position by the scale in that first piece of code?

supple citrus
#

Im trying to make it to scale, so thats to convert pixel distance to KM

short hazel
supple citrus
#

oh i see what you mean

short hazel
#

If you need to convert so you can display the values in the future, do so only when you display them

#

Units are usually expressed in meters, but you're free to interpret them as anything else

#

So if your sun is 200 "units" away, you can choose to display "200,000 KM" on your UI, by multiplying the value before displaying it

supple citrus
#

The equation for gravitational force irl uses a constant G, if I dont scale the distance wouldn't I have a different constant

open moss
#

I'm really confused. I have 3 raycasts shooting out of the player when performing a jump. One below for checking ground and two on the sides for detecting walls.
Yet for some reason I can spam jump even when not touching a wall? The raycast on the right is green indicating a hit but only up to a certain range too. Not sure how to debug this.

private bool IsTouchingWall()
    {
        // Check if the player is touching a wall
        float extraWidth = 0.01f;
        Vector2 raycastStartRight = playerCollider.bounds.center + new Vector3(playerCollider.bounds.extents.x, 0, 0);
        Vector2 raycastEndRight =
            raycastStartRight + Vector2.right * extraWidth;

        Vector2 raycastStartLeft = playerCollider.bounds.center - new Vector3(playerCollider.bounds.extents.x, 0, 0);
        Vector2 raycastEndLeft =
            raycastStartLeft - Vector2.right * extraWidth;

        // Drawing the lines for a duration of 2 seconds with a red color assuming it doesn't hit anything
        Debug.DrawLine(raycastStartRight, raycastEndRight, Color.red, 2f);
        Debug.DrawLine(raycastStartLeft, raycastEndLeft, Color.red, 2f);

        RaycastHit2D raycastHitRight = Physics2D.Raycast(
            raycastStartRight,
            Vector2.right,
            playerCollider.bounds.extents.x + extraWidth,
            wallLayer
        );
        RaycastHit2D raycastHitLeft = Physics2D.Raycast(
            raycastStartLeft,
            -Vector2.right,
            playerCollider.bounds.extents.x + extraWidth,
            wallLayer
        );

        bool isTouchingWall = raycastHitRight.collider != null || raycastHitLeft.collider != null;

        // If the rays hit a wall, draw green lines instead
        if (isTouchingWall)
        {
            Debug.DrawLine(raycastStartRight, raycastEndRight, Color.green, 2f);
            Debug.DrawLine(raycastStartLeft, raycastEndLeft, Color.green, 2f);
        }

        return isTouchingWall;
    }
supple citrus
#

Before I was just using mass = 1, G = 1, and I was trying to convert it to scale

#

Which is where everything effed up lol

open moss
short hazel
swift crag
#

one thing to note, though

supple citrus
#

Surely the relative error is the same though percentage wise

swift crag
#

you can't "cheat" by just dividing all of your numbers by a constant

#

yeah

#

Relative error is consistent.

swift crag
swift crag
prime notch
#

Hi, I want to ask question about delaying. Theres a shild gameobject(circle sprite) and it will be active when I press "P" button;

    public GameObject shield;
    int shield_hp = 3;
    bool is_shield = false;

    void Start() {
        shield.SetActive(false);
    }

    void Update(){
        if(Input.GetKeyDown(KeyCode.P)) {
            is_shield = true;
            shield_hp = 3;
            shield.SetActive(true);
        }
        if(is_shield && shield_hp > 0)
            shield.transform.position = new Vector3(transform.position.x,transform.position.y,1);
        
        if(shield_hp == 0) {
            is_shield = false;
            shield.SetActive(false);
        }
    
  void OnTriggerEnter2D(Collider2D col) {
        if(col.CompareTag("EnemyBulletTag")) {
            GameObject explosion = Instantiate(ExplosionGO); //explosion animation
            if(is_shield == false) {
                Destroy(gameObject); //destroys player ship
            }
            else {
                shield_hp--;
            }
        }
    }

What kind of code can I write so that the shield closes again after 10 seconds after opening in the territory?
Thanks!

swift crag
#

window > analysis > physics debug

#

I forget when raycast visualization was added, though

#

maybe 2022.3?

open moss
swift crag
#

scratch that.

#
        RaycastHit2D raycastHitRight = Physics2D.Raycast(
            raycastStartRight,
            Vector2.right,
            playerCollider.bounds.extents.x + extraWidth,
            wallLayer
        );

I forgot that argument 2 isn't the direction AND length

#

just the direction

swift crag
#

the visualization is a little misleading

#

i thought it was starting at the edge of the player and going that extremely short distance

swift crag
#

ah, yeah

#

brain fart

open moss
swift crag
#

let me slow down a little here :p

open moss
#

xD ok, It's weird cause when I try jump in some other part of the map, the raycast shows red like ^^

swift crag
#

You should check what you're actually hitting with the raycasts

#

you could log the collider

open moss
#

but when im near a wall, for some reason sometimes it detects it even though the raycast doesnt touch it

#

no idea what im looking at

swift crag
open moss
#

doing a simple log says what its hitting

#

But like

#

how

#

oh

#

im an idiot

#

I think

#

hold on

stuck mango
#

How can i get data of gameobject that is colliding with a inheritor of the scipt?

supple citrus
#

Im so confused

#

why is it zero lmfao

open moss
#

I was drawing the raycast distance right, but I was not throwing it the right distance 🤦‍♂️ @swift crag

swift crag
#

go to the declaration of G and hit shift-F12 with the name highlighted

swift crag
swift crag
supple citrus
swift crag
#

I saw that and figured it was going to the edge of the collider + the extra

supple citrus
#

thats it ^

#

honestly man wtf

#

cosmic ray bit flip or what

open moss
swift crag
#

it would have to be within the same class

supple citrus
#

The only thing in update is the debug logs

#

I use fixedupdate if that would also do whatever youre thinking of

#

but i never call it

swift crag
#

i wonder if that can run before Start

#

i've never thought about that

swift crag
#

Start runs the frame after an object is instantiated

#

(for things you instantiate at runtime)

supple citrus
#

oh

swift crag
#

FixedUpdate could nominally run before that happens

supple citrus
#

even still, the log remains as zero forever

#

maybe i should keep constants in a separate script and reference them?

swift crag
#

can you share the entire script?

open moss
#

what if you just make G=1 in Awake()?

supple citrus
swift crag
#

Are you getting any errors in your console from the Start method?

#

If an exception is thrown from Start, it might not get all the way to G = 1;

supple citrus
short hazel
#

Yeah that's probably what is happening right now, there could be a NullReferenceException thrown

swift crag
#

Zap

#

there's the missing context

supple citrus
#

I thought i had assigned it manually in the inspector though

open moss
#

thats your probelm

swift crag
#

you're looking at the script asset itself

#

that only matters in the editor (when you Reset a component, I think)

#

you need to assign the reference on the actual in-scene planet

#

or, if you're instantiating a planet prefab, you need to assign it after you instantiate the planet

open moss
# supple citrus

go to the gameobject in the scene and assign Sun there. I don't know when you would assign a variable in the script itself

supple citrus
#

Vector3 is 0,0,0 by default right

#

The suns actual position is 0,0,0 so i never realised something was wrong :v

#

I still dont understand where I'm meant to assign it though

open moss
supple citrus
#

Not by default

#

You click to spawn planets in

swift crag
#

whoever instantiates the planet should assign the reference

#

you probably dragged the sun prefab into the field on the script asset

#

which would be irrelevant anyway

open moss
supple citrus
#

Yeah

open moss
#

Ok go to the prefab for planet

supple citrus
#

Script called MouseClick that checks for input and instantiates planet

open moss
#

And drag in your Planet script into it

supple citrus
#

ohhhh

#

i see

#

here?

open moss
#

Now all planet prefabs spawned will have that script

#

yes

#

and now drag your Sun prefab/gameobject into there

supple citrus
#

should i get rid of this then

open moss
#

yeah

#

I have never dragged things into the script itself in Unity. I don't know what that does tbh

supple citrus
#

ahhh

#

nice

#

thanks alot 🙏

open moss
#

np <3

stuck mango
#

How can i check if player is lower than Y = -10 ?

open moss
stuck mango
#

alright, thank you

open moss
#

Global position checks the position relative to the WORLDS oigin. but local position check relative to a parent if the gameobject is a child of some parent

stuck mango
#

whats the difference

#

oh right, how do i make it use global position?

open moss
#

transform.localPosition.y is what you want for local position

open moss
#

transfrom.position.y < -10

supple citrus
open moss
supple citrus
#

i might just not risk changing it, its working now catsigh

open moss
#

you wouldnt need to get the global position of the sun and compare it with the global position of the planet for instance

stuck mango
# open moss transfrom.position.y < -10

Oh right, and one more question, i just want to make a system that will teleport the player to 0,0,0 after he falls, how do i refer to his position? Just transform.position doesnt work.

open moss
#

how do you have the player referenced in the script?

stuck mango
#

He isnt referenced, because this script is attached to him

open moss
#

so then transform.position would work just fine

swift crag
#

"doesn't work" is not helpful; you wouldn't be asking if it was working properly!

open moss
#

You would have to do something like transform.position = new Vector2 or Vector3

#

I think

swift crag
#

If your player has a Rigidbody on it, you'll need to set the rigidbody's position, instead of directly setting the position on the Transform

#

and if you're using a CharacterController, you need to disable it before setting your position (and then re-enable it afterward)

stuck mango
#
    private void AntiFall()
    {
        if(transform.position.y > MinHeight.y)
        {
            gameObject.transform.position = StartPoint;
        }
    }

I made this and this doesnt show any errors , but as soon as i start the game it locks player on 0,0,0

#

What is wrong now?

swift crag
#

you have your condition backwards

#

this sets your position when you're above the min height

stuck mango
#

oh

#

right

#

lol

undone harbor
#

I have two gameObjects with colliders and isTrigger is switched on
The OnTriggerEnter event is only working on one of them
Anyone know why?

#

Almost the same functions

swift crag
#

"almost" isn't enough, so show your code

#

we'll also want to see the inspectors for the objects

undone harbor
#
using System.Collections.Generic;
using UnityEngine;

public class plateController2 : MonoBehaviour
{
    private Animator anim;

    void OnTriggerEnter(Collider obj){
        Debug.Log("On Plate 2");
        anim.SetBool("isSteppedOn", true);
    }

    void Start()
    {
        anim = (Animator)FindObjectsOfType<Animator>()[0];
        // Debug.log(anim.GetBehaviours());
    }

    // Update is called once per frame
    void Update()
    {
       
        
    }
}```
open moss
# stuck mango ```cs private void AntiFall() { if(transform.position.y > MinHei...

instead of checking your player height for another height. You would typically use a barrier game object. And then check if your player collides with that barrier or void zone to spawn the player back to where needed. Because if you even want to move that out of bounds area in your game, you won't be able to since you are checking for a specific Y point

swift crag
#

post code like this: !code

eternal falconBOT
swift crag
#

the latter option -- inline code

stuck mango
#

I have also thought about this, but didnt think its a great idea

undone harbor
#

The inspector

swift crag
#

Is this the one that works?

undone harbor
#

Nope, this is the one that doesnt

swift crag
#

let's see the other one

undone harbor
#

The inspector for the one that works

#
using System.Collections.Generic;
using UnityEngine;

public class plateController : MonoBehaviour
{
    private Animator anim;

    void OnTriggerEnter(Collider obj){
        Debug.Log("On Plate 1");
        anim.SetBool("isSteppedOn", false);
    }

    void Start()
    {
        anim = (Animator)FindObjectsOfType<Animator>()[0];
        // Debug.log(anim.GetBehaviours());
    }

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

    }
}
#

Code

swift crag
#

and why do you think only one works?

#

is "Plate 2" not logging?

undone harbor
sullen zealot
#

hello!

myUIGroup.alpha += multiplier * Mathf.Min(Time.unscaledDeltaTime, Time.maximumDeltaTime);

is this the best way to use the eqquivalent of deltatime when timescale is 0?

open moss
undone harbor
#

That trigger event isn't triggering

swift crag
#

I noticed that your code is using FindObjectsOfType<Animator>() to grab an Animator from...somewhere, which is weird

undone harbor
swift crag
#

One of the two objects in a trigger overlap must have a Rigidbody on it. Does the player have one?

#

also, peek at "Layer Overrides" on the colliders to make sure there's nothing funny in there

undone harbor
swift crag
#

it's just weird

undone harbor
swift crag
#

seems odd that one of the two would be working

stuck mango
undone harbor
#

Found it, The collider wasn't really getting intersected

#

Thanks everyone

open moss
#

its trying to set other to player

polar acorn
open moss
#

nah he just mistyped the == check

stuck mango
#

Riight, sorry, its alright now

stuck mango
stuck mango
#

alright, thank you

open moss
#

== asks if it is equal

#

= sets

hidden sleet
#

is the start method only fired the first time something loads? if you switch scenes and go back is start called again or no?

open moss
swift crag
languid spire
swift crag
#

When you load a scene, all of the objects in the scene are loaded in

#

assuming you're not additively loading several scenes at once

hidden sleet
#

right

stuck mango
swift crag
#

the old scene is unloaded

hidden sleet
#

that's making me extra confused now X/

stuck mango
open moss
swift crag
#

but if you unload a scene, all of the things in it are destroyed

#

when you load it again, those are new objects

stuck mango
hidden sleet
#

cause to test stuff I added this to clear the items displayed. I go from one scene to another, then back to this scene, itemsdisplayed is set to 0. But as i've shown before it should add all the pairs to the dictionary after starting up again

swift crag
#

I don't want to look at screenshots

hidden sleet
#

fair enough

#

got it above alreadym lemme find it

#

something wacky is going on that I must not be understanding correctly because it isn't doing what I expect when it loads up

swift crag
#

this is redundant, by the way

#

the for loop will execute zero times if the count is zero

swift crag
#

if so, you may be relying on the exact order in which they start

hidden sleet
#

inventory itself doesn't use the start method at all

#

what I assume is happening is it's creating the itemsDisplayed dictionary on first start, and when it goes back to the scene it uses that one instead of the new one it creates, which doesn't make sense

swift crag
#

only if a reference to the dictionary has been handed to someone else

#

(and that wouldn't affect DisplayInventory)

#

it sounds to me like your inventory is empty when you come back to this scene

swift crag
hidden sleet
#

the third was just supposed to be an overview of what that method does before I pasted the whole thing.

swift crag
#

check if you're actually running that loop at all

hidden sleet
#

definitely is

swift crag
#

wait, does Inventory survive the scene load?

#

you aren't unsubscribing from inventory.onItemInventoryAdded

#

I bet you're seeing the result of the inventory invoking the old DisplayInventory's UpdateDisplay method

#

that's perfectly legal; destroyed unity objects still exist

hidden sleet
#

inventory itself is a scriptable object. so from my knowledge it should't unload

swift crag
#

it won't unload if the new scene has references to it, at least

#

scriptable objects can unload if they're left with no references

#

(putting it in a static field would also suffice)

swift crag
hidden sleet
#

all the scenes have some kind of reference to it, so I assume it wouldn't be unloaded

hidden sleet
stuck mango
#

Is there a way to make my player fall faster without changing gravity or his mass?

swift crag
hidden sleet
#

I guess it makes sense conceptually though, since inventory is now complaining about not having a displayinventory, could be that the inventory remains persistent throughout but it's the event that's gone

swift crag
#

nothing happens to the event

#

that's a member of the Inventory class

languid spire
vernal plume
#

im having an issue with inputs, ive been following a tutorial on a first person controller to use as a base for other things and for some reason everything but the jump works

#

i beleive this is everything including the code for jumping, but theres no said errors so im left trying to find it myself

hidden sleet
#

moment of truth 🤞

short hazel
eternal falconBOT
vernal plume
#

is that why my text has less colors than others?

short hazel
#

Yep

vernal plume
#

ah

languid spire
#

also @vernal plume I see no evidence whatsoever that you have tried to debug this code

stuck mango
languid spire
stuck mango
#

I dont know, i think i should change my movement system, i needed to change drag force to 5 and it made me fall much slower, but also not stick to walls and slide all around the ground

#

I need to find movement system that can use drag force equal to 0 and make me not stick to walls or slide

languid spire
#

think about it irl, if something is falling and you want it to fall faster you increase it's downwards velocity by pushing it down,, or not?

hidden sleet
eternal needle
swift crag
stuck mango
open moss
hidden sleet
#

noted, I'll be sure to keep that in mind in the future

vernal plume
open moss
#

if you want the player to fall faster, increse its gravity scale in the rigidbody

swift crag
hidden sleet
#

thanks ever so much for bearing with me X/

swift crag
#

If you want to make the player fall faster, you need to make the player…fall faster

short hazel
hidden sleet
#

my old ui slot removal method should work now, you remember the whole 'value is null thing'? I reckon this would have fixed it

open moss
short hazel
#

Yep you now need to debug why it's not jumping

#

Whether the stuff on lines 70-75 is executing, etc.

#

As they're guarded by an if statement with 3 conditions, if one of them is false, nothing will execute. You might want to print out each condition with Debug.Log() and check that they're all true

#

Or remove the conditions one by one until it starts working - then the last condition you removed was the faulty one

hidden sleet
#

when resizing a ui element like this, is there a keybind to just drag the bottom edge up and the top one moves down to mirror it?

open moss
#

alt

#

i think

#

click, then hold alt and drag

#

yeah its alt

#

make sure you click on the edge first, then hold alt and move your mouse

#

@hidden sleet

hidden sleet
#

ah there we go, cheers

#

will save a lot of time

open moss
#

holding shift also makes it move the same on all sides

#

proportional resizing

hidden sleet
#

that's neat

undone harbor
#

Do you guys create handmade animations for every character? Isn't that a lot of work?

open moss
#

hold alt+shift to proportional resizing from center of object

open moss
#

I mean there are a lot of ways to animate

#

but yeah, for 2d you make a sprite sheet of animations

#

or you make it use bones and animate the bones

#

but yeah its a lot of work

hidden sleet
#

could also use procedural animations

#

it's fun spotting their uses in games once you learn about them

dusk salmon
#

I have such a problem, created a territory unity 3d, but when I want to add more height, nothing comes out and it does not change (Same problem with downsizing)

vernal plume
#

the creator forgot to show themselves adding readyToJump = true; to start() so by default the variable was set to false

#

Thanks for the help with the IDE thing cuz I probably wouldn't have figured it out till much later

hidden sleet
#

what is the different between the yellow and grey box when resizing ui panels?

toxic latch
#

I'm messing with some very simple scripts and created a game object with a RifleStats script that has some basic values like minimum damage, maximum damage, and weight. It has a 'hasScope' bool set to false. My understanding is that I can have a 'RifleScope' script that sets that 'hasScope' bool on the Rifle itself to true, and gives a +1 to damage or whatever.

#

Am I understanding that right?

swift crag
#
float damage = rifleStats.damage;
if (rifleStats.hasScope)
  damage *= 1.25f;
#

for example

toxic latch
#

That is cleaner than how I had it. Cheers.

#

How exactly do you make it so that adding the Scope script to the gameobject satisfies that condition?

true pasture
#

I cant seem to get this to register clicks. It worked once but now it wont register.

#

the event system is new input system one with default input actions

slender nymph
#

do you have an event system in the scene? does your canvas have a graphics raycaster? does the button have some sort of graphic that that graphics raycaster can target? is there anything blocking the button?

toxic latch
#

As I mentioned, the rifle has a bool to indicate whether or not it has a scope, and I tried to have another script that set that bool to true thinking that would trigger the damage modification, but I got a 'An object reference is required for the non-static field, method, or property 'member'' error. Is that related to instantiation?

true pasture
slender nymph
#

yes, it needs some sort of image. you can probably just set the image's alpha to 0 if you want it to be invisible though

ancient island
#

Hey guys

Short question: How do I detect whether if an scene has been loaded because the application started or because another scene loaded it?

Long question: I have opening and closing animations for scene transitions. The main scene is the Main Menu, which is the first scene to be loaded when the game starts, but you can also reach it by returning from the game. In order for animations to work properly I need to check if the Main Menu scene was loaded because the application started or if it was loaded by returning from the game scene

true pasture
#

okay thanks, I added a image, but now it only wants to register the most recent version of the button I make. I have 3 identical buttons duplicated. It will only register clicks on the one I made most recently. Im very confused by that.

slender nymph
#

are they overlapping

true pasture
#

which part, is it just the button hitbox that matters?

#

like the image size

slender nymph
#

the button does not have a hitbox. the image is its "hitbox"

stuck mango
#

I have a problem with import from blender to unity.No matter what i choose in Forward and Up options, my crown is always rotated 90 degrees in unity, what causes that?

true pasture
#

heres the hitbox of the image so I dont think so

slender nymph
stuck mango
#

oh right

green copper
#

how do I hold the instantiated gameObject as a variable? I need to run a few functions on it before I "let it go" and move on to instantiating the next cell

true pasture
#

var myObject = Instantiate()

slender nymph
green copper
slender nymph
eternal falconBOT
green copper
slender nymph
#

the fact that you have no syntax highlighting for a method from the inherited class

desert elm
#

in "RaycastHit2D hit = Physics2D.Raycast(transform.position, t.position);"
what kind of variable is hit?

swift crag
#

It’s right there (:

slender nymph
#

you do realize that a variable declaration includes its type. RaycastHit2D hit = is declaring a variable called hit of type RaycastHit2D

north kiln
#

also, a position doesn't often make sense to be used as a direction, and that logic is likely incorrect

swift crag
#

indeed

junior parrot
#

Hello, why when my character is colliding with the ladder, even though he is on the ground, he is unable to jump? And how can I fix this? The code: (sorry for the english, I'm using google translator)

green copper
slender nymph
#

yes

cosmic dagger
junior parrot
stuck mango
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlatformAttach : MonoBehaviour
{
    public GameObject player;



    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Rigid")
        {
            other.transform.parent = transform;
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Rigid")
        {
            other.transform.parent = null;
        }
    }


}

I've created this code to make player stay on my moving platform, i made it move by using animator with "Animate Physics" Everything seems okay till the platform starts moving. Meaning that i cant move on it, my ability to move my player comes back after it stops. Whys that?

sacred orbit
#

is there any issues/buggy-ness with setting the camera as a child of the player?

keen dew
#

If you're having issues or bugs with that then it's because of your code, if that's what you're asking

sacred orbit
ancient island
#

How do I duplicate an animation clip? I have to make another one pretty similar to an animation I have but I don't want to do the whole thing again

#

Forget it, just had to duplicate the file

green copper
#

I'm trying to create a grid of squares on a canvas using this function and I can't figure out why it's not working. parent.transform sets the cells, which are image objects, to be children of the canvas correctly but the positioning is always offscreen and theres' always a different of like .1 instead of a full hundred

#

the node holding the script is a child of the same canvas, and is at 0, 0, 0

north kiln
#

are you sure you don't want localPosition?

#

also, don't you want to multiply, instead of add? The difference would be 1 with the current code

green copper
#

Thank you yeah that was part of the problem,

#

and yeah that fixed both problems actually thank you very much

swift crag
#

If so, you can create as many animation clips out of it as you want

ancient island
#

like changing position and so

pure viper
#

yo idk if this is the place to ask, but does anyone know how to get the word autofill to work with all the unity commands in vs code

slender nymph
#

!ide

eternal falconBOT
pure viper
#

I have it working with half of them but some like SetBool just dont autofill

#

but stuff like update and vector3 autofill

slender nymph
#

if you have followed all of the instructions for getting it configured and regenerating project files doesn't fix it, then consider switching to a real IDE that is less likely to just not work

pure viper
#

ok ill see

#

thank you

swift crag
#

note that it's likely you have not followed all of the instructions

lone finch
#

how did you start using unity?

#

i learned c# up to using arrays

#

and methods

frosty hound
eternal falconBOT
#

:teacher: Unity Learn ↗

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

topaz gorge
#

im having a massive brain fog how do i get the angle of a object that a raycast has hit

summer stump
topaz gorge
#

nah more or less the slope of a object so when i instantiate something it has the same rotation

summer stump
topaz gorge
#

I did which is where and still not doing what i was expecting it stays the same rotation

slender nymph
#

show code

topaz gorge
#
public void GetPositionAndRotationOnClick()
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            Vector3 targetPosition = Vector3.zero;
            Vector3 targetRotation = Vector3.zero;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, walkableLayer))
            {
                targetPosition = hit.point;
                targetRotation.x = hit.transform.eulerAngles.x;
                targetRotation.y = hit.transform.eulerAngles.y;
                targetRotation.z = hit.transform.eulerAngles.z;
            }

            navMeshAgent.SetDestination(targetPosition);
            ClickVFXManager.instance.InstaniateClickVFX(targetPosition, targetRotation);
        }

I even tried this second method right here which doesn't seem to produce any results either

summer stump
topaz gorge
#

i tried something else oout

#

but i have tried that

north kiln
#

What is walkableLayer

topaz gorge
#

Just the ground basically

north kiln
#

What is it literally

topaz gorge
#

i have a plane with the layer

north kiln
#

Is it a LayerMask?

topaz gorge
#

and a few cubes

#

yes

north kiln
#

well, Aethenosity is correct, you're not using the normal, you're just using the transform of the thing you hit

#

which isn't guaranteed to be rotated at all

topaz gorge
#

i tried using the normal and didnt produce any results ill show you what i had before

#
public void GetPositionAndRotationOnClick()
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            Vector3 targetPosition = Vector3.zero;
            Vector3 targetRotation = Vector3.zero;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity, walkableLayer))
            {
                targetPosition = hit.point;
                targetPosition = hit.normal;
            }

            navMeshAgent.SetDestination(targetPosition);
            ClickVFXManager.instance.InstaniateClickVFX(targetPosition, targetRotation);
        }

This is what i had before

#

endless im missing something that i just forgot im currently lost on this matter

#

and i know the targetPosition is the wrong thing

north kiln
topaz gorge
#

didnt mean to do that

north kiln
#

A normal is also a direction not a rotation, so you can't directly use it as a eulerAngle

topaz gorge
#

So lets say i want to spawn some rocks or something for example, and the terrain has hills and such how would i get the rock to match the angle of the slope, thats what im trying to achieve and i dont know if im going about this correctly

swift crag
#

transform.up = someNormalVector will align a transform's up vector with the normal vector

topaz gorge
#
public void InstaniateClickVFX(Vector3 instaniatePosition, Vector3 objectNormal)
        {
            GameObject instaniatedEffect = Instantiate(clickVFX);
            instaniatePosition.y += 0.001f;
            instaniatedEffect.transform.position = instaniatePosition;

            instaniatedEffect.transform.up = objectNormal;
        }
#

could it be something im doing with the instaniation then

sacred orbit
#

is there a difference between Input.GetAxis("Mouse X") and Input.GetAxis("Horizontal")?

topaz gorge
#

I believe the Horiziontal supports controller also vs Mouse X

sacred orbit
topaz gorge
#

Same thing Horizontal has support for controllers if im remembering correct

#

or no the Horizontal is for aswd

summer stump
topaz gorge
#

same with vertical

north kiln
topaz gorge
robust condor
#

Can I show an image of a gameobject in the inspector with custom editor window?

topaz gorge
#

But yes you can

#

Oh the partical system doesnt rotate with the gameobject

#

i got to rotate the partical directly

north kiln
# topaz gorge

That's what I'd expect to see; the up vector is aligned to the normal

short hazel
# topaz gorge i got to rotate the partical directly

Not related to your issue right now but tip for later, you can set your particle system's Stop Action (in main module) to "Destroy", so the object is destroyed when the particle system has finished rendering. That avoids making a script that destroys the object after a set amount of time

short hazel
#

If you plan to use object pooling you can also make it execute a method instead

topaz gorge
topaz gorge
lethal kestrel
#

Need some help. I have a working interactable UI that works on first start up of the game but if i stop and start the game again it stops working completly?

ivory bobcat
#

You'd probably want to provide further context (code, hierarchy, etc)

clear seal
#

is it possible to desactivate rigidbody?

#

or just the kinematic

#

with a script

#

i tried and it did not work

eternal needle
#

deactivate it in what sense

clear seal
eternal needle
#

what did you try, show the code or setup

clear seal
#

simple code

summer stump
lethal kestrel
#

This is my issue, ive honestly never had this problem before so im stumpped. My code for showing includes booleans that are all set on start and the ui is set active to false on start

summer stump
#

@clear seal Without forces acting on it, there will be nothing to ragdoll it

BUT, that WILL allow forces to act on it

eternal needle
# clear seal

This should give you an error, where are you assigning the rb

summer stump
clear seal
#

the console after runtime

#

the first log is the musket raycast

#

when it hit

#

something

summer stump
# clear seal

Yeah, so that error is for the line you showed earlier...
And that needs to be fixed obviously, before your code will work

eternal needle
ivory bobcat
#

Rb is null

clear seal
#

hold on

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

ivory bobcat
#

Serialize/publicize it and set the reference from the inspector or acquire the component in awake/start.

clear seal
#

that's prob why

lethal kestrel
lethal kestrel
topaz gorge
lethal kestrel
topaz gorge
#

ok you can remove it i got it copied

lethal kestrel
#

cheers

summer stump
# lethal kestrel whole code snippet here?

Post long code with links as shown here
!code 👇

Not sure why they said remove it, maybe I misunderstood, but everyone being able to see the code means everyone can help. Always best to keep it up

eternal falconBOT
topaz gorge
lethal kestrel
boreal tangle
#

what would be the time.delta of the first frame if its based on the last frame

slender nymph
#

print it and find out

boreal tangle
#

ok

robust condor
#

How do I assign gameobject layer to layermask set in the inspector?

[SerializeField]
private LayerMask tileLayer;
...
gameObject.layer = tileLayer;
slender nymph
#

the gameObject.layer is just a number from 0 to 32, it is not a bitmask like a LayerMask is

robust condor
#

Okay how do I convert it then?

#

LayerMask only takes strings

slender nymph
#

what? no it doesn't

robust condor
#

GetMask

slender nymph
#

yes and GetMask returns a bitmask, not the index number

summer stump
#

What are you trying to achieve?

robust condor
#

Trying to set the layer

summer stump
#

Layermask is kinda like a list of layers

robust condor
#

To layermask

nova swift
#

LayerMask.LayerToName?

summer stump
robust condor
#

@nova swiftNo

summer stump
#

And that is an xy problem. What are you trying to achieve by doing that

robust condor
#

Why not?

#

I want to define the layer in inspector and then assign it to gameobject

summer stump
nova swift
#

LayerMask.NameToLayer will give you the number you need no?

summer stump
robust condor
#

@nova swiftNo its a Layermask

#

private LayerMask tileLayer;

topaz gorge
robust condor
#

@summer stumpThat is less userfriendly and I don't get the layer dropdown

summer stump
robust condor
#

So I can't convert LayerMask selected in inspector to the layer int?

slender nymph
#

you could use an asset like NaughtyAttributes and you can use a string variable with an attribute to get a layer dropdown

slender nymph
timber tide
#

oh yeah I forgot naughty has that

robust condor
#

What a hassle

timber tide
#

otherwise you can do an onvalidate method

summer stump
slender nymph
# robust condor What a hassle

what is the actual point of what you are trying to do? perhaps a better/easier to work with solution can be suggested based on the actual problem you are trying to solve

summer stump
slender nymph
#

There is also the option of just creating an enum for your layers with the correct values assigned so that you can use that to pick a layer in the inspector

robust condor
#

I just want the layer dropdown and assign the selection when I Instantiate a gameobject instead of hardcoding numbers

slender nymph
#

why not just set the layer on the prefab and not worry about assigning it manually via code?

summer stump
robust condor
#

Well because I set ignore raycast layer when I spawn it because it sits on the cursor, and when I place it I use CheckBox and it finds itself, I need to rearrange all the code I guess

nova swift
#

How to get a pixel's depth or z position for a Unity 2D shader? For something like this:
fixed4 Frag(vert2frag i) : SV_Target
{
float4 distortedGrabPosition = i.grabPos;
float distanceToCenter = distance(i.uv, 0.5);

            fixed4 screenBehind = tex2Dproj(_GrabTexture, UNITY_PROJ_COORD(distortedGrabPosition));
            screenBehind *= i.color;

            if(i.uv.x < 0.5f) //Need to get depth/z position of a pixel/object
            {
                screenBehind.rgb = 0;
            }

            return screenBehind;
        }
slender nymph
nova swift
#

alright thank you

swift crag
robust condor
#

So if I set layer on the GO in prefab as "Tile", and I instantiate on cursor, when I try to place the obj I check if coordinate Physics.Checkbox has Tile and it finds itself on the cursor

#

I can drag it around on cursor

slender nymph
#

so disable its collider until it is placed

north kiln
#

But in this case it does seem unnecessary and the other solutions seem more sensible

lethal kestrel
topaz gorge
robust condor
#

@slender nymphThanks that works lol

#

So I have been using Physics.Raycast with a LayerMask from inspector this whole time, and it seems to have been working, why is that?

lethal kestrel
topaz gorge
lethal kestrel
#

Thats a beautiful way to structure code tho ill defintley be using that more to save lines

slender nymph
robust condor
#

@slender nymphEven tho it says int

lethal kestrel
# topaz gorge Still doing the same thing aye

yeah works perfectly if i change code save it and unity reloads everything then play works fine. When i stop the game and play again just stops showing but the debug log keeps working so its somethign to do with no setting the ui active

slender nymph
slender nymph
lethal kestrel
#

that might be the cause of it

topaz gorge
#

Do me a favor get that bug to happen and check the Ui active state when looking at a interactable and see if its active

robust condor
#

@slender nymphI see

topaz gorge
# lethal kestrel

Well i mean i need to see if the UI that you want active is actually active and it doesnt have to do with the LeanTween

lethal kestrel
topaz gorge
#

so the ui is being updated correctly

#

interesting

lethal kestrel
#

ill try remove tween and see if that changes anything

topaz gorge
lethal kestrel
#

something to do with that then

topaz gorge
#

Call SetTextInActive at the start

#

with the tween put in

lethal kestrel
topaz gorge
#

Indeed

#

instead of disabling the UI directly

#

do it with the method you already have to do that

lethal kestrel
#

doesnt even set it inactive

topaz gorge
#

change start to awake

#

btw im just having you do this for diagnosing purposes

lethal kestrel
#

same thing using awake

topaz gorge
#

ok

lethal kestrel
karmic drift
topaz gorge
karmic drift
#

I asked how, not if lol

summer stump
slender nymph
karmic drift
#

I was wondering how to setup up that type of view

#

Wondering how many degrees the wall and floor are tilted

#

I assume I would have to use an orthographic camera

topaz gorge
lethal kestrel
topaz gorge
slender nymph
summer stump
karmic drift
#

Oops didnt realize

#

My bad

timber tide
#

sprite tilting is so odd but it's actually the most performant way in Unity to prevent clipping

lethal kestrel
#

was just using it for some basic animation to learn leantween but i can go without it for now. Youve helped a ton with just getting that working properly and teaching me how to right nice code HAHA

topaz gorge
lethal kestrel
#

could honestly just be ive written the lean tween part incorrect

topaz gorge
lethal kestrel
#

same kinda thing on set start. on second start up isnt inactive

topaz gorge
lethal kestrel
topaz gorge
lethal kestrel
#

yeah super weird im gonnna focus on some more basic ui stuff and come back to animations at a later date but appreicaite the help youve been amazing

topaz gorge
#

No problem

vernal minnow
#

Alright, I feel like i have a really dumb question about getting object direction and am missing something obvious

#

I have gotten my bullet object to spawn on the character, but the bullet only goes left rather than moving based on the players rotation

timber tide
#

set the bullet direction to the player's forward direction

#

or the gun if you're spawning it from that

topaz gorge
vernal minnow
timber tide
#

yeah, forward is z facing

topaz gorge
vernal minnow
#

like my rigid2d?

topaz gorge
#

yeah if you making a 2D game

#

cause using tranforms directly can cause a lot of issues with collisions

vernal minnow
#

already fixed the issue of them colliding accidentally

#

the bullet flew off spinning originally lol

cosmic dagger
timber tide
#

oh you're using 2D

topaz gorge
timber tide
#

transforms are fine, you just need to use fixedtime

#

and then do the casting yourself

topaz gorge
#

yeah that route is also valid

timber tide
#

but if you're new to it all, using the physics from rigidbody is easier

#

especially for bullets

vernal minnow
#

welp i need to go to the code babies channel lol 🤦‍♂️

lethal kestrel
# vernal minnow welp i need to go to the code babies channel lol 🤦‍♂️

https://www.youtube.com/watch?v=wkKsl1Mfp5M&ab_channel=Brackeys follow through with this video and just see how he sets up his

Let's learn how to shoot enemies!

● Get the The Complete C# Masterclass for only $9,99: https://bit.ly/2xfXE6J

● Instagram: https://instagram.com/brackeysteam/

● Download the Project: https://github.com/Brackeys/2D-Shooting
● Get the 2D Sprites: https://bit.ly/2p6VcvH

♥ Support Brackeys on Patreon: http://patreon.com/brackeys/

·············...

▶ Play video
#

you dont have to copy but it might help you a little bit?

vernal minnow
timber tide
#

it's a specific timestep for when unity does physic calculations like collisional checks and raycasts (accumulative forces too)

vernal minnow
uncut dune
vernal minnow
uncut dune
vernal minnow
#

left and right rotate the character

#

forward and back are the movement

uncut dune
vernal minnow
#

2d

uncut dune
#

The controls dont matter

#

You want to shoot where the player is facing right?

#

You change the player rotation in the z coordinate right?

#

The player originally is looking up?

vernal minnow
#

it should always come out of the front of the character yes

vernal minnow
timber tide
#

if it spawns from an object that's facing the direction you want, you can simply use that object's direction

uncut dune
#

Are u using addforce or velocity

#

Ur using physics to do it right?

vernal minnow
#

velocity

uncut dune
#

Ok so do this

uncut dune
vernal minnow
#

should i sahre the code snippet that handles the bullet so far?

uncut dune
#

Yah sure

uncut dune
#

Ok so do it like this

vernal minnow
#

whats the proper foramt? its been a while

uncut dune
#

Just copy and paste

#

I dont have much time

vernal minnow
#

thats not the highlighted format, oops

cosmic dagger
#

!code

eternal falconBOT
uncut dune
#

Do this

north kiln
#

Just repost please

uncut dune
#

bulletRb.velocity = transform.right * bulletForce;

#

@vernal minnow this is all you need

vernal minnow
#
    {
        
                //string otherTag = gameObject.tag;
                // calculate starting X and Y coordinates
                // somewhere at the top edge of the main camera area
                float worldHeight = Camera.main.orthographicSize * 2.0F;
                float worldWidth = worldHeight * Camera.main.aspect;
                Vector2 position;
                position.x = Random.value * worldWidth - worldWidth / 2.0F;
                //position.y = gameObject.y;  // top edge

                Debug.Log("Laser 1 Fired Successfully");
                // Instantiate object at current player location
                GameObject laser = (GameObject)Instantiate(CirclePrefab, transform.position + new Vector3(0.5f, 0.0f, 0), Quaternion.identity);
                //Sets the laser on a moving course in a specified direction
                Rigidbody2D rb = laser.GetComponent<Rigidbody2D>();
                rb.velocity = new Vector2(laserSpeed, 0);
                //prevents infinite lasers from being spawned
                StartCoroutine(scheduleDestroy(2.0F, laser));
                IEnumerator scheduleDestroy(float delay, GameObject target)
                {
                    yield return new WaitForSeconds(delay);

                    Destroy(target);
                }
               
    }```
north kiln
#

Also; coroutines should not be nested in other functions, also just use the overload of Destroy that has a time parameter

uncut dune
#

Well I got to go, hope I helped

#

Oh yah if you want to destroy the bullet after some time go into the bullet script and at the start funcrion do Destroy(gameobject, seconds)

#

Seconds is the amount of seconds you want

cosmic dagger
north kiln
#

And, just reference the component you care about instead of GameObject. Referencing your prefab as a Rigidbody2D avoids you having to get the component. (Changing a type will require you re-assign it in the inspector)

uncut dune
#

Next time I'll do it the right way

vernal minnow
north kiln
#

No? Just instead of GameObject CirclePrefab do Rigidbody2D CirclePrefab, so you actually reference the thing you really care about

vernal minnow
#

ah alr

uncut dune
vernal minnow
#

before i try this bulletRb.velocity = transform.right * bulletForce; what is bullet force and bulletRb?

dense root
#

So I'm trying to change my text and it is giving me a NullReferenceException error, how do I assign text in the inspector?

public Text m_MyText;
void Start()
{
    // Text sets your text to say this message
    m_MyText.text = "Hello world";
}

void Update()
{
    if (Input.GetKeyUp(KeyCode.Space))
    {
        m_MyText.text = "My text has now changed.";
    }
}
vernal minnow
#

click the object that has this code

dense root
#

Is this for Legacy maybe?
using UnityEngine.UI;

dense root
vernal minnow
#

no

#

you drag it over

dense root
#

Still not working.

vernal minnow
#

hmn

#

send a pic of when you click the object that has the code

#

i want to see what the inspector looks like

dense root
#

I think it has something to do with public Text m_MyText;

vernal minnow
#

the text has to be assigned right?

north kiln
vernal minnow
#

alr, im lost the now, vert has ya covered probably

dense root
north kiln
#

Use the correct type?

vernal minnow
#

are you not using legacy?

dense root
#

No, I'm not

vernal minnow
#

try using legacy text

dense root
#

I'm trying to avoid that

north kiln
#

No, just use the correct type in the declaration

dense root
#

Could you, please, provide an example of a correct type and declaration?

north kiln
#

public TextMeshProUGUI m_MyText;?

dense root
#

Thank you

vernal minnow
#

is there something bad about legacy or is it just outdated?

dense root
#

AFAIK it's better to use TMP but I don't know why

north kiln
#

It's fixed resolution

vernal minnow
#

ah, bc i have both in some projects

#

oh

#

non scalar

#

ig i never noticed😂

round scaffold
weak palm
#

hey guys! What's a good way to check if a mouse button click isn't interacting a UI element?

timber tide
#

EventSystem.current.IsPointerOverGameObject()

weak palm
#

ayy thanks!

timber tide
#
//Set up the new Pointer Event
m_PointerEventData = new PointerEventData(m_EventSystem);
//Set the Pointer Event Position to that of the mouse position
m_PointerEventData.position = Input.mousePosition;

//Create a list of Raycast Results
List<RaycastResult> results = new List<RaycastResult>();

//Raycast using the Graphics Raycaster and mouse click position
m_Raycaster.Raycast(m_PointerEventData, results);

//For every result returned, output the name of the GameObject on the Canvas hit by the Ray
if (results.Count > 0)
{
    return true;
}

If you're using the "new" input system because it complains about IsPointerOverGameObject

north kiln
#

It doesn't complain to me 🤔

timber tide
#

It's been a while but I think the compiler complains if you use it inside one of the key event methods. Something about it being an update behind on the information