#๐Ÿ’ปโ”ƒcode-beginner

1 messages ยท Page 161 of 1

keen hill
#

wdym

rocky canyon
#

thanks mate ๐Ÿ™‚ lets hope the refactor isnt bad.. b/c it needs it

keen hill
#

sry if i dont understand something

swift crag
polar acorn
#

where do you set scr

#

What is the value of scr

keen hill
polar acorn
#

where do you tell the code what scr is

keen hill
#

ill send the code

polar acorn
swift crag
#

scr is absolutely not false

shrewd swift
#

bool not set = null

teal elk
shrewd swift
#

except for stuff like structs

keen hill
#

not even talking about setting it automatically in the first frame

#

cuz its not in any item's range

swift crag
# keen hill

this has absolutely nothing to do with the problem

polar acorn
# keen hill

I don't know why you're showing this code this has nothing to do with the previous question

swift crag
#

the problem is in LookAtPlayer

#

why are you showing us random code?

shrewd swift
# teal elk

so the bullet goes with the green axis, which is Y if i remember correctly ?.
this mean your movement logic is good, but the issue is the rotation your are giving to the projectile when spawning it

swift crag
# teal elk

look at how the arrows are oriented for the projectileSpawnPoint object

keen hill
#

the bool is set in this code to false

#

so the src is not null its false

swift crag
#

They're not the same type and they're not even in the same class

shrewd swift
#

maube use a look at, but this depends if you have a gameobject always tracking the cursor position

polar acorn
swift crag
polar acorn
#

in the script with the error

#

how do you set src

#

what value does that variable hold

keen hill
#

i thought it holds bool

#

from the other script but idk now

swift crag
#

You have a very weird misunderstanding of how references work

keen hill
#

probably

swift crag
#

scr is a field of type PlayerInRange

#

It is not a bool. Nor is it a float or LayerMask or Transform or any other type that happens to be stored in a field on PlayerInRange

#

It is a PlayerInRange

keen hill
#

okay

swift crag
#

The reason that scr == true worked is because of how Unity lets you convert any unity object into a boolean implicitly

#

e.g.

shrewd swift
# teal elk

could you tell us what is this transform coming from ?

swift crag
#
if (scr) {
  Debug.Log("scr is a valid unity object");
}
#

This has nothing to do with InItemRange

#

It is completely unrelated.

keen hill
#

ok so

#

is there a way

swift crag
#

scr.InItemRange would be the value of InItemRange stored in the object referred to by scr

keen hill
#

i can reference a bool form the other script

swift crag
#

Sure. Assign a reference in the inspector, then use scr.InItemRange to read the boolean field

shrewd swift
keen hill
#

so private bool src;

polar acorn
swift crag
#

The reason that happened was because value was not a UnityEngine.Object derivative

#

UnityEngine.Object is where the implicit conversion to bool is implemented

#

You can't just throw any type into an if statement and have it convert to a bool

shrewd swift
#

ah okay

swift crag
#

so List<int> would not work

keen hill
polar acorn
swift crag
shrewd swift
#

thats why for ie you cant do if GOref

swift crag
#

You need to make incredibly tiny changes

keen hill
#

i just want the reference

swift crag
#

You also need to pay attention

polar acorn
swift crag
shrewd swift
keen hill
swift crag
shrewd swift
#

๐Ÿซ 

cursive viper
#

sum1 pls help been stuck on this for hours now

shrewd swift
#

then why do i remember does error i had

swift crag
keen hill
#

cuz im having problems with understanding complex stuff in a language i dont know well

lofty sequoia
#

unity allows null checks by just saying if(the object)

swift crag
swift crag
#

Specifically look at the "Serialized references" section

swift crag
shrewd swift
#

also, in chsarp can you create a method so it gets used when trying to print or evaluate a class instance ? can you even do this with structs ?

like in python, __str__

keen hill
keen hill
#

cuz i will be creating a lot of items with this script

#

and i dont want to assign everything manually

swift crag
#

If every object will refer to the same ItemInRange component, then consider the "Singletons" section

#

sigh

scarlet skiff
swift crag
#

there's enough spam in the world already. i'd rather not get buried under more of it

swift crag
stuck palm
#

if a parent is disabled and enabled, will the childs "onenable" get called?

swift crag
frosty hound
#

If you can't help someone, you don't need to be their ChatGPT mediator. @cursive viper

swift crag
#

also, I presume you mean deactivated and activated

stuck palm
#

yeah

#

that was quick damn

#

i'll do something else then thanks

slender nymph
swift crag
#

you can use OnEnable if you want to run every time you become enabled

#

wow, the documentation for OnEnable is bad

#

This function is called when the object is loaded.

#

true, but....

keen hill
swift crag
keen hill
#

i have to see it work and see how every single line works

swift crag
#

people aren't going to walk you through literally every step

keen hill
#

but there isnt a tutorial how to link a bool from another script

swift crag
#

Of course there is.

keen hill
#

cuz it probably requires one line of code

swift crag
#

oh my god there are so many tutorials about this

#

you've been linked to one

shrewd swift
# swift crag `ToString()`
class someClass {

public string ToString(){ return "this is me"; }


}
someClass instance = new()
Debug.Log(instance) //prints out "this is me"
instance.length //prints out the length of string  "this is me"

string test = "yoo";
if (test = instance) //this would not error

so this examples would work ?

keen hill
shell sorrel
swift crag
#

You can implement one if you want.

keen hill
#

been tyoping for like 15 minutes to just link a bool from another script lol

shrewd swift
swift crag
#
public static implicit operator string(MyType self) {
  return "hello";
}
#

I want to say that's correct.

#

This enables a type to implicitly convert to another type when needed.

shrewd swift
swift crag
#

it explains quite a lot

shrewd swift
#

can this be used for a struct ? since struct can have methods

swift crag
#

this compiles.

scarlet skiff
swift crag
#

ToString is simply a method that's defined on every object

#

like, every C# object, not just every Unity Object

proper hornet
#

hey would any body tell me what is the best thing to download if your trying to learn c sharp visual studio code or visual studio

swift crag
swift crag
#

But that's different from the language being told "hey, type Foo can implicitly convert to a string"

cursive viper
#

visual studio code is just a text editor with some fancy features pretty much

swift crag
frosty hound
swift crag
#

I use VSCode for a lot of things, so I picked it

#

(VS is also not really available my macbook)

stray wraith
#

I have a movement script and I want it to have no velocity cap when falling down. The way to do this as far as I know is to set the rigidbody's drag to 0 however I also want the movement to feel responsive, what do I do?

swift crag
#

is the problem that you ice-skate around?

#

or are you talking about movement specifically when falling?

stray wraith
swift crag
#

One option would be to apply your own drag.

#
Vector3 fallingVelocity = Vector3.Project(rb.velocity, Vector3.down);
Vector3 movingVelocity = Vector3.ProjectOnPlane(rb.velocity, Vector3.down);

movingVelocity = Vector3.MoveTowards(movingVelocity, Vector3.zero, Time.deltaTime);

rb.velocity + fallingVelocity + movingVelocity;
stray wraith
#

generally when airborne

swift crag
#

This would slow you down by 1 meter per second per second, but only horizontally

#

Proper drag should be proportional to your current speed.

#

Unfortunately the obvious answer doesn't quite work right...

#
Vector3 fallingVelocity = Vector3.Project(rb.velocity, Vector3.down);
Vector3 movingVelocity = Vector3.ProjectOnPlane(rb.velocity, Vector3.down);

movingVelocity = Vector3.MoveTowards(movingVelocity, Vector3.zero, movingVelocity.magnitude * Time.deltaTime);

rb.velocity + fallingVelocity + movingVelocity;
#

Although, if it's happening in FixedUpdate, then it's probably fine.

#

(this code slows you down twice as fast if you're moving twice as fast, which is roughly how drag should work)

cursive viper
#
if (ballGrabbed && !grabPressed)
{
    ball.GetComponent<Collider>().enabled = false;

    ballRb.velocity = velocity;
    ballRb.MoveRotation(Quaternion.RotateTowards(ball.rotation, ballHolder.rotation, rotationSpeed * Time.fixedDeltaTime));

    return;
}

if (Physics.Raycast(cam.position, fwd, 5, layerToHit) && grabPressed)
{
    Debug.DrawRay(cam.position, fwd, Color.green, 10);

    ballGrabbed = true;
    grabPressed = false;
}

Anyone know what I could do here? If I re enable collision in between the if methods, the ball will immediately be "grabbed" again due to the second if method running right after, but if I don't re enable collision the ball will no clip through the floor

stray wraith
#

thanks

rocky canyon
#

Since we're speaking on Directions and stuff (earlier) I have a question..

  • I wrote out this script (trying to make it generic enough to use thru-out my project
    • Everything works pretty much the way I think it should only the additionalOffset part of it

The additional offset was originally b/c the UI i was using on it was backwards and used a 180 offset so it would be facing directly..
That's when I noticed how the Transform gizmo would look upwards first and then back down.. I'm pretty sure this is the way I'm adding the offset
(causing quaternion magic stuff)

heres the script : https://gist.github.com/SpawnCampGames/47b2edb673714b5c6fa1e7c30b371e6c
and how I add that offset // Apply additional offset directly to the desiredLookTarget desiredLookTarget += additionalOffset;

anyone know of a better way to add the offset?

teal elk
#

i tried trasnform.forward and my bullet is now going only in the direction , why the y and x is static,

shrewd swift
shrewd swift
#

like

// inside a class
public static implicit operator int(MyType self) {
  return 3;
}

myClass inst = new()

if (inst > 3) // this would not error
rocky canyon
# rocky canyon

wait, this may be correct, it may just appear wrong to me.. i'm going to test w/ some raycast and drawlines right quick

swift crag
#

the most straightforward way to do this is a serialized field: you drag an object into a field in the inspector and you're good

#

If you don't want to have to manually assign it, then you must find another way to get that reference. if everyone uses the same reference, then the singleton pattern is appropriate (as described in that link)

#

otherwise, you'll need some other mechanism to provide the reference

polar acorn
#

Important note: There is no alternative to learning how to reference objects. That is programming. Almost every problem is some form of "How do I get a reference from here to there"

#

There is no shortcut

rocky canyon
# rocky canyon

ya, so i think this is okay. i think it appears to be looking upwards b/c it is.. when the camera goes across it, it has to look upwards b/c its so close to it

odd mason
#

trying to set an objects sprite to this other one and it wont recognize it unsure as to what im doing wrong

rocky canyon
#

show where you declare BerryBushEmpty

odd mason
rocky canyon
#

u have to tell the IDE what it is...

modest dust
rocky canyon
#

and which one it is

odd mason
rocky canyon
odd mason
#

yeah i get it now

#

jsut didnt think i had to declare it for sprites for some reason dont know why i thought that tbh

rocky canyon
#
  • Hey Unity, I need to use a sprite;
    • I see that, what sprite are you going to use
  • This one
    • Thank's, I'll remember you're going to use a Sprite named whateverYouNamedIt, and you want that sprite to use this image/sprite
odd mason
#

thanks for the help btw

rocky canyon
#

that'd be extra beneficial ๐Ÿ˜„

odd mason
#

actually i think there might be a way to do that if im understanding this post im reading correctly

rocky canyon
#

ya, I don't do runtime creation stuff like that yet

odd mason
#

ah i see

rocky canyon
#

but good resource

vague dirge
#

Hi, I'm using Nomnom's Raycast Visualization package in my project but it doesn't seem to work, doe smone knows why pls ?

vague dirge
#

Ngl what's that ๐Ÿ˜… ๐Ÿ˜‚

north kiln
vague dirge
north kiln
#

Then I can only presume you're not calling nomnom's via code, or you're casting in a completely different place

vague dirge
#

I just finally fixed it, thanks for the help

scarlet skiff
#

how do i set the object reference to an instance of an object

rich adder
scarlet skiff
rich adder
#

"first one" ?

topaz pendant
#

this means that your script looked for an object with the component (script) PlayerMovement in the scene, but there were none

slender nymph
# scarlet skiff first one i think

"i think" you should verify that by looking at the stack trace. although i can guarantee that it is the first one since that is the only line shown that can throw that exception

rich adder
#

if you mean FindObjectOfType then you have no GameObject with PlayerMovement script on it

scarlet skiff
rich adder
#

also why aren't you just putting a field in the inspector and assign reference that way

scarlet skiff
#

well it says the error coems from update

topaz pendant
#

navarone is right, you should almost never use a FindObjectOfType inside an Update method as this is a very expensive operation, you should most likely set this in Start or elswhere

scarlet skiff
#

this count as a GameObject with the script, right

topaz pendant
#

if the object or the script are disabled, FindObjectOfType won't find it

rich adder
scarlet skiff
topaz pendant
#

theres an error, you probable changed the name of the script or the name and the class don't match

scarlet skiff
polar acorn
scarlet skiff
#

but its still compile error

#

before that the code could run without issues

polar acorn
scarlet skiff
#

wait i foudn the problem

#

somehow in one of the scripts a letter was removed fro mthe name and the script was saved ๐Ÿคฆ

#

lols

#

okay so this is how the code is now, i have put the player in the serialized field, but the update isnt really update the fireballs rotation based on the plays position... any1 know why?

polar acorn
supple citrus
#

I have 2 object classes, Suns and Planets. I want a list of all current gameobjects in the scene. How would I make a list store every instance of 2 different classes?

#

Or would I use a structure other than a list

polar acorn
supple citrus
#

Is that easy once you've already done a bunch of stuff with the original classes

polar acorn
#

If you need a list that contains both of them, chances are they have some sort of shared functionality you can move into the parent class

supple citrus
#

ehh suns are immobile and planets move around the suns. I want to use the list to store all current planets/suns so I can go through each element in the list when saving the current scenario as a preset that can be loaded later

polar acorn
#

So then presumably any functionality related to saving the objects can be put in the parent object

supple citrus
#

if i named the new class test would I just change the original scripts by making
the sun class into Sun : test
and planet into planet : test ?

polar acorn
supple citrus
#

yeye

#

ty

#

Oh does everything In the planet and sun script go into 1 big mega script for the new class

polar acorn
#

Anything shared between the two goes into the new class

white pelican
#

Not sure how visible this is, but when running my game there seems to be some sort of white border that flickers, not sure if this is a visual glitch or I may have done something to enable this

timber tide
#

you got the camera selected

#

also try posting videos from the computer itself ;p

white pelican
#

I don''t actually think I have a video capturing application currently ๐Ÿ˜…

timber tide
#

I think it's the camera? Could be UI related, but turn off gizmos in the top right to ignore it completely

white pelican
#

hmm good call, but it seems to still persist

slender nymph
#

you didn't turn off gizmos

white pelican
#

not this?

timber tide
#

yeah it's the camera's frustum

slender nymph
#

you've toggled gizmos off for the scene view

white pelican
#

oh wow... Well I did think that this was most likely just me not knowing where some very common button is supposed to be located, TYSM both of you <3

rocky canyon
#

file sizes are pretty small

white pelican
#

ahh tysm was about to get obs lol ^^ but might get that instead :)

rocky canyon
#

OBS is good for recording high quality, but ShareX allows u to just record sections of the screen (or windows that u select) and the file sizes are small enough to share pretty quickly

rare basin
#

If I modify the ScriptableObject values (int, float) via code in runtime, do they save between sessions?

rich adder
#

not in build

slender nymph
#

if you modify an asset then those changes persist in the editor. but not in a build

rare basin
#

so if i restart the editor

polar acorn
#

This is a good argument in favor of just never mutating ScriptableObjects. It can lead to difficult bugs that behave differently in development environments that don't happen in builds

rare basin
#

the changes will be present i made in runtime?

polar acorn
#

If the change occurs in a build, there is no asset and it will reset when you restart the program

wintry quarry
rare basin
rare basin
#

okay

polar acorn
rare basin
#

got it thanks

scarlet skiff
rare basin
#

but if i use SetDirty()

#

it will be permament even in build?

scarlet skiff
rare basin
#

one more thing I dont understand. When making changes via runtime (in the editor) to the scriptable object, it is permamently - i get it. But I don't have any changes to commit in git. When I set the ScriptableObject as SetDirty() then i do have changes to commit in git, why is that?

wintry quarry
#

Changes in git means the file on disk changed

#

Which is different from the object in memory

#

When you set it as dirty the editor saves the in-memory changes to the file

rare basin
#

ah, alright

#

cheers

polar acorn
#

Is the sprite facing up, to the right, etc.

scarlet skiff
potent echo
#

Hey folks, I've been having a strange issue while writing a script that's used to figure out whether a gameObject is colliding with something from a certain direction. The error occurs whenever the subject gameObject initially comes in contant with the ground, setting IsGrounded to be true (which works fine), however the IsOnWall and IsOnCeiling properties are set to true as well for some reason, before quickly being set back to false. This creates a handful of bugs related to the gameObject's movement and collision handling. I've been struggling with this one for a while, so any help is appreciated.

Here's the script I've got:

// Had to cut off some parts of the script that (I hope) weren't related
public class TouchingDirections : MonoBehaviour
{
    public ContactFilter2D castFilter;
    public float groundDistance = 0.05f;
    public float wallDistance = 0.2f;
    public float ceilingDistance = 0.05f;

    BoxCollider2D touchingCol;
    Animator animator;

    RaycastHit2D[] groundHits = new RaycastHit2D[5];
    RaycastHit2D[] wallHits = new RaycastHit2D[5];
    RaycastHit2D[] ceilingHits = new RaycastHit2D[5];

    [SerializeField]
    private bool IsGrounded;

    [SerializeField]
    private bool IsOnWall;

    public Vector2 wallCheckDirection => gameObject.transform.localScale.x > 0 ? Vector2.right : Vector2.left;

    [SerializeField]
    private bool IsOnCeiling;

    void FixedUpdate()
    {
        IsGrounded = touchingCol.Cast(Vector2.down, castFilter, groundHits, groundDistance) > 0;
        IsOnWall = touchingCol.Cast(wallCheckDirection, castFilter, wallHits, wallDistance) > 0;
        IsOnCeiling = touchingCol.Cast(Vector2.up, castFilter, ceilingHits, ceilingDistance) > 0;
    }
}
polar acorn
# scarlet skiff right

You can set the object's transform.right to the direction from the object to the player

#

You can get a direction between two objects by subtracting their positions and normalizing

scarlet skiff
polar acorn
#

Just set transform.right to the direction vector

scarlet skiff
#

can you break it down a lil more

#

im not fully getting it

polar acorn
#

Two simple steps:

  1. Get the direction from the fireball to the player
  2. Set transform.right to that
timber tide
#

right is on your right

polar acorn
#

You can get the direction between two objects by subtracting their positions, and normalizing

scarlet skiff
scarlet skiff
#

is this how u meant by get the direction

polar acorn
scarlet skiff
#

ok so i looked into what normalizing meant and this is what i get:
Normalizing a vector means scaling it to have a length of 1 while preserving its direction.

What i have done so far is subtracting their positions and making a vector by it, and since i have to normalize it has ot mean we want it to be a vector.

what i see as the next step is to normalize, but i dont have a clue what it would mean in this situaiotn or how to do it, what is meant by "length of 1"

small dagger
#

Hi guys, I am trying to learn NavMesh and how to figure an AI that chases the player (in this picture, the green cylinder). The player is supposed to collect the gold orbs, however, if the green monster collides with the gold orbs, they are dstroyed, depriving the player of the point. However, the NavMesh agent seems to have trouble following the player when the player is surrounded by the orbs, is there a way to have the NavMesh agent ignore the gold orbs so it doesn't affect it's navigation?

slender nymph
rocky canyon
#

@small dagger do the coins have mass? why do they stop the navmesh

#

or do they carve out the navmesh?

small dagger
small dagger
eternal needle
timber tide
#

could consider using different layers for each of these types, otherwise may need to look into a smaller cast range if you really need specific flags to always be set

#

usually better to just not work with exclusive logic

wind raptor
#

I have a unity desktop application that connects to several microcontrollers. I am wanting to create a UI to interact with these devices, but accessible from another device. Say from the web browser of a phone or laptop. Main priority is for it to be accessible by devices on the local network, but connectivity over the Internet would be nice too. And while I'd prefer for the UI to be web-based, I wouldn't be opposed to having a separate Unity application on the connecting device.

What is the best way to accomplish this? It would be nice to build out the UI within Unity and avoid dealing with HTML or something.

small dagger
eternal needle
eternal needle
shell herald
#

a random range is different every time it is called right? so if i put a random range in update its gonna be different every frame?

small dagger
#

every frame, update is called, and it will run the random function that produces a new number every time it's ran

wind raptor
shell herald
#

so this is gonna play the death1 sound 33% of the time randomly?

eternal needle
rich adder
hybrid vine
#

Guys do you know why the Button Click sound is not playing when i click the button? I have 3 buttons: Play, Options, and Controls, where i set an On Click action to play the sound (that i attached to an empty object, then drag and dropped it into the slot under the Main Camera for which i wrote the code (e.g, public void playSound1() { soundPlayer1.Play(); } ). All of the 3 buttons were set up that way, but now only the Play button plays the sound and the other 2 dont?

shell oriole
#

Hi, I need help. I need to store possibly hundreds of data items, but they all need to be different datatypes, how can I store these? I want to use an array/list. I just need a way to store large amounts of data that are all different datatypes without too much strugle. Thank you!

hybrid vine
#

ther are no errors in my code, and the sound actually plays if i set it on "play on awake", just doesnt play when i click the button

teal viper
eternal needle
shell oriole
teal viper
shell oriole
shell oriole
#

each event has an id

teal viper
meager sentinel
teal viper
shell oriole
hybrid vine
#

here is the inspector of the button, sound attached to an empty object, and main camera (under which the code that plays the button click sounds is):

shell oriole
hybrid vine
#

wdym?

#

oh yeah this is the code

shell oriole
#

In your code it just looks like a bunch of functions with nothing to run them

#

i saw it before dont worry about resending it

teal viper
meager sentinel
hybrid vine
#

ah but wouldnt those functions just play the sounds that were attached int he inspector?

shell oriole
#

you need to run them

#

functionname();

#

after you declare them

#

i think at least

teal viper
meager sentinel
meager sentinel
hybrid vine
shell oriole
#

you need to run it in the function that detects when the button is clicked.

teal viper
meager sentinel
#

click it is pressing E, i said it wrong

teal viper
#

But at the timing after pressing E.

meager sentinel
#

exactly like before

teal viper
#

Is it active in the hierarchy?

meager sentinel
#

yeah

teal viper
#

Okay, then debug what object you're hitting.

cursive viper
#

https://hastebin.com/share/odobocebas.csharp

not really necessary to read this script to get what im trying to do but just put it here for context, but how would I switch to grabbing an objects rotation from a raycast hit instead of from a reference??

meager sentinel
teal viper
teal viper
# meager sentinel like this?

No... In your other script. We already established it doesn't enter into Interact. You want to figure out how far it goes and what condition is not getting passed.

meager sentinel
teal viper
#
            {
                Debug.Log($"hit object {hitInfo.gameObject}");
meager sentinel
teal viper
teal viper
#

Wat?

#

!ide

eternal falconBOT
meager sentinel
#

that's why

teal viper
#

Then get an ide and configure it before proceeding with your issue.

#

Is that VS code? Follow the guide above to config it.

meager sentinel
teal viper
#

Now print the name of the hit object.

meager sentinel
#

Also, this part of the script stills dont work

teal viper
meager sentinel
#

It should print yes but it doesn't

#

and i also did what you said and stills doesn't

teal viper
meager sentinel
#

Wait... I think i know the problem

teal viper
#

Possible causes, wrong ray direction, distance, lack of active colliders.

meager sentinel
#

the script should be on the player right?

teal viper
#

You tell me..? Does it need to be on the player?

meager sentinel
#

Like to make the raycast

teal viper
#

You're the one that knows the intention behind the code.

#

ATM your ray uses the interact source transform for ray origin and direction.

#

So it doesn't really matter where the script is. What matters is what transform is assigned to that field.

meager sentinel
#

k am dumb

#

i had to make the source be the player

#

that's why i hate 2 min tutorials

teal viper
#

Tutorials shouldn't replace your head.

#

You need to fully understand what you are doing even if you are following a tutorial.

high wigeon
#

so um....does anyone even know what this means?

round umbra
#

hello im working on a player movement script i countered a few issues on the way,

my player jump is really inconsistent
i have been stuck for a few days and taught well why not just ask

https://gdl.space/axebilikam.cs

teal viper
round umbra
#

alright wil do

teal viper
meager sentinel
#

is just that i see a guy that does extremely explanatory tutorials (where i learn from) but i never saw him teaching about Raycast

round umbra
#

appreciate it dlich its working

meager sentinel
teal viper
meager sentinel
#

oh bro am sorry

#

damn the dumbest error i had

#

i forgot to change the variables name

shell herald
#

so im trying to switch to the new input system. if i get this right, callbackcontext.performed is similar to OnButtonDown and callbackcontext.cancelled is similar to OnButtonUp?

polar acorn
#

What line

teal elk
#

I'm trying to implement a muzzleflash sprite to be set active when the player fires bullete , but due to me setting false in the same fucntion , it never shows , is there a way for me to activbate and then deactivate once the bullete is shot ```cs

[RequireComponent(typeof(PlayerController))]
public class WeaponController : MonoBehaviour
{
[SerializeField] private PlayerData playerData;
[SerializeField] private GameObject muzzleFlash;
[SerializeField] private Projectile projectile;
[SerializeField] private Transform projectileSpawnPoint;
private float timeTofire;
private Vector3 mousePos;

private void Start()
{
    muzzleFlash.SetActive(false);
}

public void Fire()
{
    if (Time.time > timeTofire)
    {
        muzzleFlash.SetActive(true);
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
       Projectile newProjectile = Instantiate(projectile, projectileSpawnPoint.position, Quaternion.identity);
       newProjectile.SetFireDir((mousePos - transform.position).normalized);
       newProjectile.SetSpeed(playerData.ProjectileSpeed);
       timeTofire = Time.time + playerData.FireRate;
        muzzleFlash.SetActive(false);
    }
}

}```

timber tide
#

can do an animation clip and play once

#

actually that may still be disabled, so perhaps coroutine then disable

polar acorn
#

Slot[_weaponSlot] is null

#

You never actually put a weapon list in that slot

timber tide
#

or just dont disable and use an animation play once

teal elk
shell herald
#

i am super confused with implementing the new Input system. how do i implement button presses in the update instead of its own void? i basically want this, but instead of the normal inputs, the new ones. is that possible?

shell herald
#

thx

rich adder
#

what are you confused on?

twilit pilot
#

it would be helpful to start by making a list, rather than an array of lists

rich adder
#

indeed

#

or in this case a dictionary would make more sense

polar acorn
#

You've made an array that can hold 6 lists, but you never made any lists

shell herald
rich adder
#

there are dozens wdym

teal viper
#

Google๐Ÿช„

shell herald
#

or this thing?

rich adder
#
[SerializeField] private PlayerInput inputz;
void Update()
{
    if (inputz.actions["Fire"].WasPressedThisFrame())
    {
        Debug.Log("Fire pressed");
    }
}```
shell herald
#

ahhh, figured that was what i was missing

#

thx

rich adder
#

sorry you want Pressed not Released . fixed

#

np

shell herald
#

yep, works like a charm

hybrid vine
#

why does unity keep outputting "Can not play disabled audio source" in the console, when the audio source its talking about is literally enabled

slender nymph
#

sounds like it isn't enabled

hybrid vine
#

frustrating af because ive spent the past hour and a half trynna solve this ๐Ÿ˜ญ

#

how? its ticked idek how

slender nymph
#

prove that the audiosource you are calling Play on is not disabled

hybrid vine
slender nymph
#

show the code where you call PlayOneShot

hybrid vine
#

the debugs is to try and figure out what is wrong

shell sorrel
#

90% chance you are not referencing the audio source you think you are

rocky canyon
#

i almost guarentee theres more than 1 audio source hiding up in there

slender nymph
#

at a guess i'd say it's probably a prefab being referenced. or one of the many disabled objects in that scene

shell sorrel
#

also seems complicated having these button and sound pairs

hybrid vine
#

i have 6 audio sources and 6 buttons, Play, Options, and Controls have their own audio sources (empty objects with audio clips dragged into them), and the last four are back buttons for each menu (3 audio sources with the same audio clip)

rocky canyon
#

you should use the context part of the debug to show u exactly which source its referring to..

shell sorrel
#

think i would just have a component on each button that calls some other system to play teh sound

#

could make it automatic by implement it in the IPointerClickHandler for the click component

rocky canyon
#

^ like an AudioManager static class.. that just plays UI sounds

#

doesn't even need to static.. could just have a singular gameobject with an audiosource to play all the clips

hybrid vine
#

but how would i specify a specific audio source to be played under specific buttons, if they are all attached under one gameobject

slender nymph
#

you don't need a separate audio source for each of those buttons though

#

just one audio source for all of your UI sounds

shell sorrel
#

well if its UI, its not going to be positional audio

#

so 1 source can be used for all ui sounds

hybrid vine
#

i just wanted different buttons to have slightly different sounds

shell sorrel
#

yes you can sitll do that

hybrid vine
#

but honestly at this point i dont mind having just one, i just want this to work already xD

shell sorrel
#

1 audio source with a script on it, then each button has a play on click component that references the audioclip you want to play

#

then it can call the system that has the audio source tell it to do a PlayOneShot and pass the clip in

hybrid vine
#

before this it all worked perfectly, but i played audio clips directly, and they were too loud, so i decided to use audio sources to change some of the sound parameters. Now i cant play them

hybrid vine
#

its so late at night rn lmaooo, but i wanna get this done tonight instead of leaving it to tmr

shell sorrel
#

if you dont have time, would just leave yourself a few notes

rocky canyon
#
public AudioSource clickSounds;
public AudioClip clickUnit;
public AudioClip clickGround;

public void PlayButtonAudio()
{
            // Generate a random pitch within the specified range
            float minPitch = 0.95f;
            float maxPitch = 1.05f;
            float randomPitch = Random.Range(minPitch,maxPitch);

            // Set the random pitch and play the sound effect
            clickSounds.pitch = randomPitch;
            clickSounds.PlayOneShot(clickGround);
}```
#

this is how i deal with multiple sounds with the same function, anytime i click the ground it sounds a bit different..

#

then i can call other methods that use different clips

#

but thas just 1 way

polar acorn
rocky canyon
#
Debug.Log($"Audiosource played",gunAudioSource);
gunAudioSource.PlayOneShot(machineGun2Echo);
shell sorrel
#

yeah my method is i have a SO type called ClipBucket, which contains a list of audio clips, a volumn range and a pitch range

rocky canyon
#

id just add a little debug to all the places u call oneshot in ur scripts

shell sorrel
#

that way i can easily add varration

rocky canyon
#

they'll be able to be clicked and show which one logs b4 the error

hybrid vine
#

could it be saying that because of my BACK buttons? since they ARE indeed disabled due to them being under different menus that get enabled with a button press. I tried fixing that by delaying the sound playing a few seconds after the entire menu is enabled but that didnt work

shell sorrel
# rocky canyon smart

yeah all the sound manager stuff for playing sounds will aceept a clip and some args or a clipbucket

shell sorrel
rocky canyon
#

i like.

#

i might do the same

shell sorrel
#

the last number on the right is for a weight so can make some more common then others

hybrid vine
#

whaaaaa that looks incredibly convinient

#

how can i make that?

rocky canyon
#

building ur own tools is magical..

#

a little extra work at the start.. but so much time saved later

rocky canyon
#

its an audiomanager singleton, that builds itself

#

then u got all these methods i pre-wrote.. where u can just pass in audiosources or clips as arguments

odd valley
#

guys how to make a fading in and out black screen transition between scenes

rocky canyon
#

ur still seems more scaleable lol

shell sorrel
#

yeah pretty similar, audio manager has pools of sources with different settings too

rocky canyon
#

i just enable/disable it w/e i need

rocky canyon
#

the garbage collection is probably awful tho

shell sorrel
hybrid vine
#

icl imma just go sleep and come back tmr, thx for your help lads

odd valley
#

kk thx

shell sorrel
#

have done a more complex approach for other types of screen transitions like it circle closing on the character etc

#

but if i just want a fade to black no need to make it complicated

odd valley
#

alr thx man

rocky canyon
#

30 Second Fade Transition ๐Ÿ˜„

cosmic dagger
rocky canyon
#

oh, interesting!

amber spruce
#
void FixedUpdate()
{
    Vector2 direction = (Vector2)target.position - rb.position;

    direction.Normalize();

    float rotateAmount = Vector3.Cross(direction, transform.up).z;

    rb.angularVelocity = -rotateAmount * rotateSpeed;

    rb.velocity = transform.up * speed;
}

any idea why this doesnt work

#

it just goes straight up

civic adder
#

I'm having problems making an Array for a Unity Object

amber spruce
shell sorrel
#

and is this for a 2d game?

amber spruce
#

yeah

shell sorrel
#

what is rotateSpeed

amber spruce
#

200

shell sorrel
#

well should angularVelocity not be a vector

slender nymph
#

not for a rigidbody2d

shell sorrel
#

ah i am thinking 3d rb

#

not sure the cross product is doing exactly what you want

amber spruce
#

im following this tutorial for it https://www.youtube.com/watch?v=0v_H3oOR0aU

Letโ€™s make a Heat-Seeking Missile that will follow around a target!

โ— Download the Project: https://github.com/Brackeys/Homing-Missile
โ— Unity Particle Pack: https://goo.gl/2SdCiU

โ™ฅ Support Brackeys on Patreon: http://patreon.com/brackeys/

ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท

โ™ฅ Donate: http://b...

โ–ถ Play video
shell sorrel
#

since its 2d would be tempted to just do a ATan2 and do the math manually

slender nymph
#
  1. not a code question
  2. you are using a much newer version than that tutorial uses. have you checked to see if you can just create a ParticleSystem object from the Create menu?
amber spruce
slender nymph
#

id:browse to find a relevant channel. but i also already answered it

ashen wind
#

I'm trying to make a selection box when you drag your mouse, and I've got code like this

        Vector3 mousePosition2 = Input.mousePosition;
        selectionRect = new Rect(
            Mathf.Min(mousePosition1.x, mousePosition2.x),
            Screen.height - Mathf.Max(mousePosition1.y, mousePosition2.y),
            Mathf.Abs(mousePosition1.x - mousePosition2.x),
            Mathf.Abs(mousePosition1.y - mousePosition2.y)
        );

        Vector2 min = Camera.main.ScreenToWorldPoint(new Vector2(selectionRect.x, selectionRect.y));
        Vector2 max = Camera.main.ScreenToWorldPoint(new Vector2(selectionRect.x + selectionRect.width, selectionRect.y + selectionRect.height));

        Collider2D[] colliders = Physics2D.OverlapAreaAll(min, max);
#

but there's some kind of offset

#

it doesn't select items that are inside the box

#

and it selects items that aren't inside the box

wintry quarry
shell sorrel
queen adder
#

yay! i can save tilemaps now

slender nymph
#

in the hierarchy not your project window

shell sorrel
#

can convert it to degrees by multiplying it by Mathf.Rad2Deg

ashen wind
#

and above it if I go on the bottom of the screen

glad widget
slender nymph
#

okay at this point you've been directed to the correct channel to ask this in. for future reference, when you are trying to get something specific then you need to ask about that.

lofty gazelle
#

is the grid component matched to the unity grid when its 1, 1, 1?

amber spruce
potent echo
teal viper
shell sorrel
#

its mostly used for tilemaps

teal viper
#

Aah

shell sorrel
#

though can use it for convert differnet grids coord systems to worldspace and back again

teal viper
#

Read the message wrong. My bad.

shell sorrel
#

iirc at 1, 1, 1 and square grid it is matched

#

but only for that 1 grid type, since you can perfectly match a hex or isometric grid

amber spruce
#

anyone know why i cant change the angular velocity of my rb2d

teal viper
amber spruce
#

im so dumb

teal viper
#

And of course there's always the case where you interpret the issue incorrectly.

lofty gazelle
#

ahh you guys talked about it

cosmic dagger
# rocky canyon oh, interesting!

it simplifies having trigger/collision methods on multiple components. it's much easier to use one component and call methods from others. you can even separate the trigger and collision events into their own components. i made for enter, stay (maybe not), and exit . . .

humble condor
#

can anyone know why the hell this funtion not work?

rocky canyon
#

i didnt~~ know~~ think about using events like that w/ the physics calls

cosmic dagger
humble condor
cosmic dagger
cosmic dagger
eternal needle
#

you arent using volume in your code

cosmic dagger
#

also, the parameter volume isn't used at all . . .

humble condor
calm coral
#

Hey I have a problem with my interface, I've copied and pasted a .cs script from one project to another and for some reason it can't recognize it

rocky canyon
#

Way to confuse D:

calm coral
rocky canyon
#

its only 4 lines, copy it delete that one ^ create a new one paste it in and save

#

make sure the editor is compiling it before u try using it again

calm coral
rocky canyon
#

attch?

vestal ether
#

This is my code for my player. I have forwardForceX set to -2000, but in my unity it has it set to -5000. Why?

rocky canyon
#

u can right click the interface name and try renaming it thru the IDE

eternal falconBOT
glad widget
#

This should be simple but i cant find a tutorial on this, how can i make a bullet explode when it hits something

Here is the code for my bullet:

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

public class Bullet : MonoBehaviour
{
public float life = 3;

private void Awake()
{
    Destroy(gameObject, life);
}

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Destroyable"))
    {
        Destroy(collision.gameObject);
        Destroy(gameObject);
    }
}

}

rocky canyon
#

usually that will rename the filename too.. so u can trigger a recompile like that

cosmic dagger
calm coral
eternal falconBOT
vestal ether
glad widget
#

heres the code in the website

calm coral
rocky canyon
#

idk how to force it to recompile

vestal ether
rocky canyon
#

its in an editor folder*, not sure that matters either

glad widget
rocky canyon
#
  • to make a prefab u can just drag a gameobject into the project window (the folders)
glad widget
#

oh awesome

rocky canyon
#

to instantiate it at a certain place, or whatever

glad widget
#

thank you

rocky canyon
#

thats stopping unity from compiling?

vestal ether
cosmic dagger
calm coral
rocky canyon
#

its in the editor folder.. maybe u need to call the namespace?

#

using UnityEngine.Editor or is it Unity.Editor

#

the error says it

#

thats it, i shoulda asked about errors earlier

vestal ether
rocky canyon
#

-2000 even a valid volume setting?

calm coral
rocky canyon
#

well the error says its in a different assembly

cosmic dagger
# humble condor

i found the code i used when messing with the audio mixer. don't mind the parameter . . .

public void SetVolume(AudioMixerArgs  e) => e.Mixer.SetFloat("Volume", Mathf.Log(e.Volume) * 20);
vestal ether
rocky canyon
#

ah nvm, true wrong person

cosmic dagger
rocky canyon
#

maybe random knows

vestal ether
cosmic dagger
#

also, your force value should not be that high . . .

cosmic dagger
rocky canyon
#

his simple interface .cs class isn't being exposed to the script he's trying to derive it from

vestal ether
rocky canyon
#

its good in the editor.. but not in the VS, altho it is in an Editor folder, and the error is the *are you missing a using statement.. * error

cosmic dagger
# vestal ether How do I make it back to default
  1. reset the script from the inspector (this will remove any values you changed back to default)
  2. remove the script, then add it back, effectively resetting all values
  3. or just simply change the value to what you want

i really don't see why this is an issue . . .

rocky canyon
#

did u even try adding the editor using statement?

calm coral
#

Now I have this error

rocky canyon
#

it says assemb , - Editor in the thing, so i was almost certain alongside the error, thats the issue

slender nymph
#

That interface needs to come out of the editor assembly. That's the only solution that makes any sense because they can't build with it in there even if they got the assembly reference

rocky canyon
#

thats probably whats stopping the thing from compiling

cosmic dagger
rocky canyon
#

oh see, i didnt even know that.. soo good stuff lol

vestal ether
calm coral
#

It doesn't highlight "MonoBehaviour" anymore

vestal ether
cosmic dagger
cosmic dagger
calm coral
cosmic dagger
#

@vestal ether i suggest following a tutorial to learn how to interact with your code and what the inspector does . . .

cunning rapids
#

How to not strecth the texture for the floor?

vestal ether
cosmic dagger
tepid summit
#

or

#

edit the png size

cunning rapids
tepid summit
#

ok'

#

i didnt think of that so good job

shell herald
#

how can i disable a sprite renderer based on a bool?

queen adder
#

spriteRenderer.enabled = false

shell herald
#

damn. makes sense

queen adder
#

Hey guys, I'm using Navmesh to make it so the npc follows me but for some reason it keeps bouncing off of me as if it's hitting a forcefield. I used stopping distance to make sure it didn't push me but I don't know how to make him stop.

ivory bobcat
#

Maybe comment out the translate line.

wintry quarry
queen adder
queen adder
#

@ivory bobcat Okay so, it's back to do the same thing. Any other suggestions?

humble condor
lusty marten
#

I have a base scriptable object class Item, then one that inherits from it ToolItem : Item. ToolItem has it's own variable that is not on the base Item class.

When I have a List<Item> I cannot access the unique variables on ToolItem even though they can be added to the List.

Something I'm not grasping about scriptable objects and inheritance. I assumed since ant item that inherits from the base Item class can be added to the List<Item> then I could also access the variables unique to each class that inherited from the base class.

dusty coral
teal viper
dusty coral
#

why isn't this working?

lusty marten
# teal viper You can if you cast it to the type you're interested in, although, that is not a...

I'm just experimenting with scriptable objects and maybe some sort of inventory.

So to make up an example on the spot

  • Item type A, B and C each have unique variables associated with them, but all inherit from the base Item class which has the standard variables like name, item sprite, etc.
  • Then have all of the items A, B and C in one List or array, then be able to access those unique variables on each for something like a method that scans a players inventory, searches for items of type B, which has a unique variable on it which the method references.
glad widget
#

!code

#

weird

eternal falconBOT
glad widget
#

oh nice

teal viper
queen adder
teal viper
ivory bobcat
queen adder
#

yeah

#

At first it stopped like it should but it's back to do it

ivory bobcat
#

Make sure to save the script.

#

Other than that, destination should be relative to player position

#

So it'd have something to do with player

#

Did you make any changes since the error had gone away?

queen adder
glad widget
#

I want to make it where if the player collects 3 keys, a text will pop up on screen saying "You Win!"

So far, my game has collectable keys that can be collected, all that stuff is done with, all i have left to do is make it where if all 3 keys are collected, youll get a message saying "You Win!"

How do i do this? Ill send pictures of my code, and if you want them in text form just say the word and ill send them through gdl.space asap

#

and if you need any other screenshots or information again just ask and ill send them asap

lusty marten
teal viper
#

There might be cases where casting to the appropriate type might be okay. It really depends on the exact scenario of where you access the object.

frank flare
#

How do I remove the turning lock and slippery while turning and the thing where the cow flops?

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class DriveCow : MonoBehaviour
{
    private Rigidbody Cube_rb;
    public GameObject Cube_gameobject;
    
    private Rigidbody Cube_rb2;
    public GameObject Cube2_gameobject;
    
    private Rigidbody Cube_rb3;
    public GameObject Cube3_gameobject;
    
    private Rigidbody Cube_rb4;
    public GameObject Cube4_gameobject;
    private float speed;
    private float turn_speed;
    
    
    void Start()
    {
        Cube_rb = Cube_gameobject.GetComponent<Rigidbody>();
        Cube_rb2 = Cube2_gameobject.GetComponent<Rigidbody>();
        Cube_rb3 = Cube3_gameobject.GetComponent<Rigidbody>();
        Cube_rb4 = Cube4_gameobject.GetComponent<Rigidbody>();
        speed = 20;
        turn_speed = 2;
    }
    
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            Cube_rb.velocity = new Vector3(-1, 0, 0) * speed;
            Cube_rb2.velocity = new Vector3(-1, 0, 0) * speed;
            Cube_rb3.velocity = new Vector3(-1, 0, 0) * speed;
            Cube_rb4.velocity = new Vector3(-1, 0, 0) * speed;
        }

        if (Input.GetKey(KeyCode.D))
        {
            Cube_rb3.velocity = new Vector3(0, 0, 1) * turn_speed;
            Cube_rb4.velocity = new Vector3(0, 0, 1) * turn_speed;
        }
        if (Input.GetKey(KeyCode.A))
        {
            Cube_rb3.velocity = new Vector3(0, 0, -1) * turn_speed;
            Cube_rb4.velocity = new Vector3(0, 0, -1) * turn_speed;
        }
    }
}
#

this is my code

dusty coral
#

why is he levitating

nocturne phoenix
#

can someone explain how to use transform direction to me?

teal viper
teal viper
nocturne phoenix
# teal viper What's the actual question?

i am trying to make it so my character moves in the direction i am looking if i press key to move forward

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

public class Aim : MonoBehaviour
{
    float yAxis;
 
    float xAxis;
    [SerializeField] float Sens;


    // Start is called before the first frame update
    void Start()
    {
  
    Cursor.lockState = CursorLockMode.Locked;
    }

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

        Vector3 rotate;

        GameObject player = GameObject.Find("Player");

        yAxis = Input.GetAxis("Mouse Y");
        xAxis = Input.GetAxis("Mouse X");


        rotate = new Vector3(yAxis, xAxis * Sens, 0)
        transform.eulerAngles = transform.eulerAngles - rotate;
    }
}
#

the aim script

#

lemme send the movement one

#
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] int speed;
    Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
 
        rb = GetComponent<Rigidbody>();

        speed = 5;

    }

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

    {

        float verticalInput = Input.GetAxis("Vertical");
        float horizontalInput = Input.GetAxis("Horizontal");


        if (Input.GetButtonDown("Jump"))
        {
           rb.velocity = new Vector3(rb.velocity.x, speed, rb.velocity.z);
            Debug.Log("Jumped!");
        }

        rb.velocity = new Vector3(horizontalInput * speed, rb.velocity.y, verticalInput * speed);
   
    }
}
#

someone told me i would need to use transform direction

#

but i cant figure out how exactly do you use transform direction even tho i understand what it does

teal viper
#

You probably want to use transform.forward * vertical input * speed, and transform.right * horizontal input * speed to calculate the velocity.

nocturne phoenix
teal viper
#

You can check it in the documentation.

frank flare
#

My current problem is that the cube goes literally on a direction Vector3.new(-1, 0, 0), instead of moving somewhere like forward or backward or right or left

Cube_rb.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb2.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb3.velocity = new Vector3(-1, 0, 0) * speed;
Cube_rb4.velocity = new Vector3(-1, 0, 0) * speed;
nocturne phoenix
#

so i shall use transform

#

instead of vector3

#

that would work probably

#

as its local space not world space

teal viper
nocturne phoenix
nocturne phoenix
#

so backwards and forward both is going to be vertical

dusty coral
nocturne phoenix
#

nvm i figured an answer

dusty coral
#

the char collider is right on the ground but it still can't detect the collission

#

-_-

teal viper
dusty coral
#

i fixed that but the drop sound is still not being called when char collider hits the ground

#

it only works if i push the player under the ground

nocturne phoenix
#

@teal viper how would i go around doing horizontal movement?

  if (Input.GetButton("Vertical"))
        {
            rb.velocity = transform.forward * verticalInput * speed;
        }

        if (Input.GetButton("Horizontal"))
        {
            transform.Rotate(new Vector3(rb.velocity.x , rb.velocity.y , horizontalInput * speed));
        }```
#

the vertical movement works fine

#

i think i fucked up a little with horizontal tho

#

wait why am i using transform.rotate anyway

tender walrus
#

hi all, I'm new to .NET and unity and I'm trying to import a library from github but I'm getting a lof of compilation errors. I tried googling solutions without much success.
Attached you can find a picture of the repo containing the files i'm trying to get (https://github.com/jfg8/csDelaunay) . What I did is I cloned the project, placed it in the assets in my unity project, then I opened it with visual studio and ran the commands said in the readme, then opened it with unity but got a lot of complilation errors/warnings

GitHub

Voronoi Diagram C# Implementation. Contribute to jfg8/csDelaunay development by creating an account on GitHub.

#

Sorry if it's a stupid question, but could someone explain to me how I can import this library in my unity project ?

teal viper
teal viper
nocturne phoenix
#

i never even noticed transform.right

#

๐Ÿ˜…

#

wait so transform.right is just transform.forward but horizontal?

eternal needle
#

you can think of transform.right as the tranform.forward, but on the right ๐Ÿคฏ

nocturne phoenix
#

๐Ÿ˜ญ

#

actually no i am dumb

#

my bad

#

i wrote transform.forward

#

intsead of right

#

again

dusty coral
nocturne phoenix
#

so i can preserve the velocity of other directions

#

making strafes possible

#

and make it so if the player looks down he doesnt stop moving or if he looks up he doesnt start flying?

teal viper
# dusty coral why not

Because the sound doesn't play..? Although it's really a speculation without seeing your code/setup.

eternal needle
#

How could starting a task race against cancelling said task? Also you generally dont need task or async stuff in unity

dusty coral
teal viper
dusty coral
#

it only gets triggered if i put half othe player in the ground

teal viper
dusty coral
teal viper
#

Run them on the main thread.

teal viper
eternal falconBOT
nocturne phoenix
teal viper
# dusty coral

And you want to put a log outside of that if statement. How are you gonna know if the method is even called?

nocturne phoenix
#

like you mean i shall create 2 vector3s

#

and then put them for rb.velocity

#

or what?

#

sorry if i am sounding dumb

#

thats probably because i am dumb

#

but alright

teal viper
nocturne phoenix
teal viper
#

Since transform.forward and transform.right are 2 vectors.

#

But you want them both combined.

nocturne phoenix
#

i can use transform.forward and transform.right at the same time??

#

but then how would i do that

teal viper
#

Vector math๐Ÿช„

nocturne phoenix
#

i cant put transform.forward / transform.right in vector 3 tho

teal viper
#

Did you not learn about vectors in school?

dusty coral
nocturne phoenix
teal viper
#

How do you combine 2 vectors?

nocturne phoenix
teal viper
teal viper
nocturne phoenix
teal viper
#

Pretty sure that's covered by 10th grade. If you don't remember, now's a great time to go learn that.

eternal needle
#

@little garden
no need to keep hopping with the question, didnt get to fully but im pretty sure you can cancel a task no problem before its run. If you're trying to make sure it's not cancelled beforehand, then you need to structure your game beso it's not even possible to do so. Still, not sure what the use case of this is. You dont need to go through async hell for unity

dusty coral
eternal needle
teal viper
little garden
# eternal needle <@431378688257556480> no need to keep hopping with the question, didnt get to f...
new Task(...);
cancel
// task may actually run here
new Task(...)
// both tasks may be scedualed to run but not actually started yet here
cancel
// or here

to ensure the above does not race, would we need to launch two tasks ?

new Task(...) // actual
new Task(...) // monitor
monitor.join(); // ensure actual task has actually began executing

actual task will cancel monitor task when it begins

monitor task will while loop for a token cancellation

teal viper
eternal needle
#

Yea totally, was just saying it's likely they didnt learn it before.

eternal needle
#

And you can see the downsides of trying to use it in unity

eternal needle
# nocturne phoenix idk i am still in 10th grade

If you're interested in learning vectors properly, Khan academy should have a lot of good videos on it. Im sure YouTube also has a lot since it's a highschool concept. You should be fine with most unity math knowing just the basics which is like magnitude, normalized vector, addition, scaling a vector. Theres more but that's a good starting point

little garden
teal viper
gritty stratus
#

The biggest trick I've ever used, and it is amazing for ForLoops.

If you are working with a static int, and want to see the values for it. Here's an example of how I got to see that value for Health.

public int _health;```
It's a meme in terms of naming convention, but it allowed me to check the conditions regarding a loop that wasn't working, which managed physical heart sprites. And that simple fix, now allows me to get sleep.
#

All you have to do to initialize it is to use in Start/Awake.
health = _health;

This was essential for a hearts/lives manager system I just completed

eternal needle
#

Learning how to debug is the most important. Also static health is definitely ... questionable

gritty stratus
eternal needle
#

Do you know how to print something to the unity console?

teal viper
eternal needle
#

Also this entirely doesnt make sense to begin with. Assigning a non static int to the value of a static one once wont make the values equal at all times. You'll have to change both everytime you change one

gritty stratus
gaunt ice
#

you need to know how to reference an instance

eternal needle
#

You should 100% do some basics of c# before continuing in your journey. This code will be awful for you to edit later

dim halo
#

does someone know why I cant add my script as a component to the model that I have, I'd appreciate any kind of help>

eternal needle
#

Yes you will get an error because now you cannot reference the variable in a static way. Maybe you only have a few references for it. If you try to change this like a month later, its gonna require changes in a lot more scripts

dim halo
#

okay

dim halo
eternal needle
#

Recompile should just be done automatically for you when you save and go back to unity

dim halo
#

okay

gritty stratus
# eternal needle You should 100% do some basics of c# before continuing in your journey. This cod...

I am not the biggest fan of my setup even, because it does have ONE side effect function, which annoys me still.

But the setup I had to go with looked like this (which is only part of the three scripts required to make this work)

    {
        defaultLives = 4;
        health = 4;
        _health--;
 
        for(int i = 0; i < HeartUiObjects.Count; i++)
        {
            {
            if(_health < i + 1)
            {
                HeartUiObjects[i].SetActive(false);
            }

            else
            {
                HeartUiObjects[1].SetActive(true);
                HeartUiObjects[2].SetActive(true);
                HeartUiObjects[3].SetActive(true);
            }
            }
        }

        if(health == 0)
        {
            
        }
    }```
nocturne phoenix
slender cargo
#

bool IsGrounded()
{
return Physics.Raycast(transform.position, -Vector3.up, 1.5f);
}

Would this be a routine? Or what do you call this method?

gaunt ice
#

i will call it private method

remote sequoia
#

Do the "if" term at the top and the "else" term at the bottom work together? How can I separate it?

gaunt ice
#

no, it works with second if

remote sequoia
#

But there was a bug

restive ember
#

If you want it to work with the first if

#

Put it below the first if

gaunt ice
#

if, else if, else
basic control flow

remote sequoia
#

ฤฐm going to try thanks

restive ember
remote sequoia
remote sequoia
#

ฤฐts for normal enemy

restive ember
#

You want it to work with both Iโ€™m assuming?

remote sequoia
#

Second and third about faster enemy

#

Nope

#

The first one is one piece and the remaining two need to work as one piece

restive ember
#

Then change the second if statement to else and put the code in the 2nd and 3rd piece into that else statement

modest dust
#

Either do

if (...)
{...}
else if (...)
{...}
else
{...}

Or

if (...)
{...}
else
{
  if (...)
  {...}
  else
  {...}
}
remote sequoia
modest dust
#

Or you can return early from the first if statement:

if (...)
{
  ...
  return;
}
if (...)
{...}
else
{...}
modest dust
#

Then you have other two

remote sequoia
#

Yea

modest dust
#

But they're basically the same, as far as I'm seeing correctly

remote sequoia
tawdry dome
#

I've used serializefield in my code in order to access variables from the inspector, but the variables are not showing up in the inspector, any help?

gaunt ice
#

!ide

eternal falconBOT
modest dust
remote sequoia
#

Thanks for help guys

tawdry dome
north kiln
modest dust
tawdry dome
#

I've got the correct one configured, but still not serializefield, additionally I would like to use the newest version, how could I do that?

#

I have also checked for the errors, I fixed some but I don't know how to fix the rest
They are all on line 52, I have linked it

#

I don't know why the || isn't working as an or operator, and I don't know why there are expected ; and ), I didn't think they were required there?

modest dust
#

You have an extra ) in your if statement

#

Right before ||

tawdry dome
#

Oh ok thanks

modest dust
#

And your IDE still doesn't look configured

#

Did you follow all the steps in the provided link?

tawdry dome
#

I will look through it again, but you fixed the code so thank you

#

Everything is working, so I think it is configured correctly

modest dust
tawdry dome
#

Oh really? That is strange. I can't fix it currently as I have to go, but I will save your links and make sure to sort it out later

#

!ide

eternal falconBOT
nocturne phoenix
#

chat is there a way to do something like
rb.velocity = new Vector3(verticalInput * speed * transform.forward, rb.velocity.y, rb.velocity.z); (that doesnt work)

#

and uh no i cant learn vector math rn i will try to learn it later tho

#

i got a test tommorow of another subject

#

๐Ÿ˜ญ

rare basin
#

why doesn't that work?

#

you can assign any vector3 to rb.velocity

nocturne phoenix
#
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] int speed;
    Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
 
        rb = GetComponent<Rigidbody>();

      speed = 5;

    }

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

    {

        float verticalInput = Input.GetAxis("Vertical");
        float horizontalInput = Input.GetAxis("Horizontal");


        if (Input.GetButtonDown("Jump"))
        {
            rb.velocity = new Vector3(rb.velocity.x, speed, rb.velocity.z);
            Debug.Log("Jumped!");
        }

        rb.velocity = new Vector3(verticalInput * speed * transform.forward, rb.velocity.y, rb.velocity.z);



    }
}
#

vertical and horizontal is float

rare basin
#

do you have your IDE configured?

nocturne phoenix
#

wdym?

#

its setup for unity

#

if you mean that

rare basin
#

you are passing a Vector3

#

as a x parameter

#

it requires a float

nocturne phoenix
rare basin
#

x,y,z

#

rb.velocity = new Vector3(x,y,z)

nocturne phoenix
#

oh yeah

rare basin
#

and you are passing vector3 for the x

#

and it has to be a float

nocturne phoenix
#

so whyd i get that error

rare basin
hexed terrace
#

transform.forward is a Vector3..

nocturne phoenix
hexed terrace
#

No buts

rare basin
#

but what

#

you cannot pass Vector3 instead of a float

nocturne phoenix
#

how would i take its value then?

rare basin
#

value of what

nocturne phoenix
#

i basically need to use transform.forward so it behaves according to rotation

#

but that fucks up the fact that i cant define other velocity

rare basin
#

set the rb.velocity to verticalInputspeedtransform.forward

#

then set the y and z to the before value

hexed terrace
#

forward is the Z axis, and you're putting this in the X axis

nocturne phoenix
#

or its not

#

and i am just dumb

#

which i am

#

so makes sense

hexed terrace
#

no, of course not, otherwise I wouldn't have said it ๐Ÿ˜„

nocturne phoenix
nocturne phoenix
#

how

rare basin
#

what do you mean how

#

how do you modify just y value of any vector3?

nocturne phoenix
#

oh just that?

#

alr ty

#

i mean i just modify the value like i would modify a normal vector 3 correct?

rare basin
#

try it

#

and you tell me

rare basin
nocturne phoenix
#

let me try

rare basin
#

it's not any special vector3

nocturne phoenix
#

i might be wrong but will i do

            rb.velocity.y = rb.velocity.y;```
rare basin
#

what would that change?

#

you are assign a value to the same value

#

non sense

nocturne phoenix
#

no like

#

2nd part i will replace by old value

#

but how will i take the old value tho

#

will i store it in a variable?

rare basin
#

cache it before you assign the new one

nocturne phoenix
#

sorry if i am sounding dumb

nocturne phoenix
rare basin
#

just think

#

its not that hard ๐Ÿ˜„

#

read it

#

stop asking question you can just see yourself

nocturne phoenix
#

no like why is not letting me modify .y

#

here only

#

outside i can modify it

#

nvm i cant

#

so rb.velocity.x is just a readable term

rare basin
#

yup

#
Vector3 velocityVector = rb.velocity;
velocityVector.y = initialYValue;
velocityVector.z = initialZValue;

rb.velocity = velocityVector;
frank flare
#

how can I use here Vector3?

rare basin
#

what do you mean

#

you can use whatever you want, it doesnt have to be transform.forward

frank flare
#

I've got the same code but a different problem

nocturne phoenix
frank flare
#
Cube_rb.velocity = new Vector3(-1, 0.04f * speed, 0) * speed;
frank flare
#

here the problem is that it goes not forward

nocturne phoenix
hexed terrace
#

Z is forward, you have Z as 0.. of course it won't move

nocturne phoenix
#

i stored theo ld values

#

thats fine

rare basin
frank flare
#

yes, it goes up but even if I use

Cube_rb.velocity = new Vector3(-1, 0, 0) * speed;
rare basin
#

show what are you doing

nocturne phoenix
#

but i cant use the values together