#💻┃code-beginner

1 messages · Page 4 of 1

dusk musk
#

That did it! Thank you so much.

oblique gazelle
#

hello

#

player not aiming right pls help

fringe pollen
oblique gazelle
#

yes

#

Need help to rotate player to target

#

anyone could help?

verbal dome
#

Trolling 100%

#

The conversation just keeps resetting lmao

polar acorn
hazy iris
#

Tutorial for begginer on discord where ?

eternal needle
#

and the unity !learn pages

eternal falconBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

oblique gazelle
#

target to aim in unity

#

pls help

#

here is my game

sage tulip
oblique gazelle
#

what

#

you see image

#

=!=!=!

sage tulip
eternal needle
#

surely after 5 hours of repeating the exact same question, you'll eventually realize that you're not asking properly

hazy iris
oblique gazelle
#

pls hrelp me

oblique gazelle
#

anyone jump in voice?

#

pls help

queen adder
polar acorn
fickle plume
#

@oblique gazelle If you continue to spam the channel and ignore people helping you you'll be muted again.

sage tulip
# oblique gazelle pls hrelp me

I am trying, but you will not engage in actual conversation.

People get help here every day.
Most people have no idea what they are doing.

But they do get successful help, when they

  1. Properly answer questions
  2. Follow instructions
  3. Speak in complete sentences

What I did find, is a channel with a video, with what I think you are asking about:
https://www.youtube.com/watch?v=CxI2OBdhLno&ab_channel=RoyalSkies

Mouse control is one of the easiest ways to control looking around in a game. It also turns out to be very straight forward code. Learn the basics of Mouse Input in Unity over the next 2 minutes!

Movement Control Code Tutorial: https://www.youtube.com/watch?v=iu5hw8WFmmQ&list=PLZpDYt0cyiusT185fsSTEU1ecr8CcTYMP&index=9

If you enjoyed this video...

▶ Play video
#

He makes short videos that get straight to the point.

verbal dome
#

Oh royal skies does unity content too? Cool. I know him from those blender quick tutorials

sage tulip
#

He did, before switching to Unreal.

oblique gazelle
#

pls join voice

polar acorn
sage tulip
queen adder
ebon lark
#

he is trolling

polar acorn
north kiln
#

!mute 266251267314155520 3d you've been muted before, and now you're muted again. This is your final warning, if all you want to do here is spam requests for help instead of listening to answers and learning, you will be banned next time it happens

eternal falconBOT
#

dynoSuccess ryldex was muted.

sage tulip
#

Unless there is some method to the madness

#

Anyway, that's over now.

queen adder
#

Some people dont want help, but solution to all of their problems within one sentence

uncut dune
#

Im getting the error going to the second image

slender nymph
#

which is line 27

uncut dune
#

ohhhhhhh

#

ok thank you so much

slender nymph
#

yes. your error is one line 27 of BossCutsceneAnim.cs

uncut dune
#

it is going to one script but referencing something in other

uncut dune
#

thank you so much

#

I found the solution

slender nymph
#

you should still read that link i sent so you can familiarize yourself with how to solve these issues yourself in the future

uncut dune
#

I have managed it manny times

#

I was just finding it weird

#

but I saw the problem after u said line 27

slender nymph
#

yes and the link i sent shows you how to read the error so you can see where it is occurring

uncut dune
#

also do u have any idea why the custom crosshair is so big in the web build but way smaller in downloadable

slender nymph
#

this is a code channel

uncut dune
zealous oxide
#

https://hastebin.com/share/udinijakiz.csharp hey friends, i've tried to set a max zoom in/max zoom out float on a dynamic zooming camera for a 2d platformer... but its not working. if i hold down the space bar it can zoom out indefinitely.

wintry quarry
#

not without seeing your code

slender nymph
#

it's not clear from the video what is causing it. but if you think it is a code issue, then share the relevant code

wintry quarry
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

slender nymph
#

oh also, is there a reason the player is a child of the tilemap? 🤔

wintry quarry
#

and in fact has a Tilemap component and tilemap renderer component :O

slender nymph
#

oh wow yeah, this is all kinds of weird

wintry quarry
#

I mean what I said ¯_(ツ)_/¯

#

Hard to say. There are several things wrong

#

probably start over

#

don't use Tilemaps as characters

#

share your code as per the bot message above

#

then try again

#

If you're following a tutorial I'd say start from the beginning

slender nymph
#

i'm gonna bet that the player tilemap has a few other tiles on it and maybe even a tilemap collider which is causing the rigidbody2d to make it freak out. and then the transform.Translate in the code is probably making it worse

wintry quarry
#

thank you - yes mixing transform.Translate with Rigidbody motion is definitely a bad idea

#

but it's only one of your problems

slender nymph
#

when using a rigidbody you should stick to the rigidbody for movement rather than moving it via the transform. that way you won't be ignoring colliders when moving and actually moving with physics.
there are a few ways to move a rigidbody, you can assign its velocity, you can use AddForce, or you can use MovePosition. the latter is intended to be used with kinematic rigidbodies though

hidden bone
slender nymph
#

stuttery camera rotation usually means you are multiplying your mouse input by deltaTime

hidden bone
#

i dont think i am

#
        mouseY = Input.GetAxisRaw("Mouse Y");
         
        yRotation += mouseX * sensX * multiplier;
        xRotation -= mouseY * sensY * multiplier;

        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        camHolder.transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
        orientation.transform.rotation = Quaternion.Euler(0, yRotation, 0);
        transform.rotation = Quaternion.Euler(0, yRotation, 0);```
slender nymph
#

why do you have both a sensitivity and a multiplier? 🤔 the sensitivity is the multiplier

hidden bone
#

good point

#

im gonna try removing it

slender nymph
#

but it's also possible that you are simply moving/rotating the camera on a different time step than your other objects. or perhaps doing it earlier in the frame.
my advice is to just use cinemachine. it's super easy to set up for a basic camera like this

hidden bone
#

cinemachine?

#

idk what that is

#

but uh

#

this wasnt a problem before

#

this became a problem after i tried to add networking

#

and i've since then given up on the networking and reverted the scripts

#

i only changed 2 of them and looking through them, i cant seem to find anything that could be the issue

hidden bone
#

perhaps its some setting in the editor i need to change?

slender nymph
#

then provide more context

hidden bone
#

should i show the hierarchy and the inspector?

slender nymph
#

sure. also more of the code

hidden bone
#

camera is under cameraholder

slender nymph
#

your sensitivity is about 100x higher than it should be

hidden bone
#

the camera has a follow script

hidden bone
slender nymph
#

but why

#

just remove the multiplier and set the sensitivity to 1

hidden bone
#

cuz 100 is an easier number for me

#

makes more sense to me at least

#

the camera follow script is just private void Update() => transform.position = cameraPosition.position;

tawdry rock
summer stump
slender nymph
hidden bone
#

no i mean its easier if i wanna change the sensitivity

slender nymph
#

how is that any easier

hidden bone
#

cuz then i can change it to something like 120 rather than 1.2

#

and i like whole numbers

hidden bone
slender nymph
#

depends, do you move your other objects in FixedUpdate? if yes, then yes moving the camera at the same rate you move your other objects is ideal. if not, then try LateUpdate so your camera isn't potentially updating 1 frame late

hidden bone
#

i move the player in fixed update

#

do i need to change the scripts in any way or can i just turn the Update into FixedUpdate

slender nymph
#

okay well i'm going to go back to my earlier advice and say just use cinemachine

hidden bone
#

alright thanks

autumn cargo
#

hey I already posted this but just gonna try again.

This is suppose to generate a line between the startpoistion and end position.

the line doesn't appear.

Ive checked the camera, layers, line width etc,

made sure the points are in the right place

but it still won't display the line

I made sure the function was running with debug.

polar acorn
#

Is the line renderer set to display in world space

autumn cargo
#

aw shit

#

it is now but it still didn't appear

eternal needle
polar acorn
#

Try logging startPosition.position and endPosition.position and see if they're where you expect them to be

autumn cargo
#

whats in the gameobject transform doesn't match up with what displayed in debug.log

#

hold on

#

why would they be so different

rare basin
#

you didint even show what are you debug loggin

#

how can we know

autumn cargo
ivory bobcat
#

Are you referencing prefabs? Do the objects have parents?

autumn cargo
#

they are children of the player object so they move with the player object

ivory bobcat
#

Is the parent scaled?

rich adder
autumn cargo
#

I made the ball smaller recently.. but before I made the gameobject

#

so I guess it is scaledi think

ivory bobcat
autumn cargo
rich adder
polar acorn
# autumn cargo

The inspector shows local position, relative to the parent. You're printing the world position.

last grove
autumn cargo
#

I had no problem with creating a line renderer from a drag motion so odd

ivory bobcat
#

If anything consider printing the local position and seeing if it's the value you want. I'm not able to see the behavioral changes since I'm not in front of your computer. See if the values are accurate and go from there.

autumn cargo
#

the position from the debug.. how can I see if they are the same as the ones in the inspector if inspector is world view?

ivory bobcat
#

The inspector values are the local position

autumn cargo
#

they are now the same

#

still nothing

#

also just tried a new shader for sprite diffuse, and default sprite shader nothin

sage folio
#

hey i have this issue in my 2D platformer controller where on my tileset, the sloped terrain will have the 'player' slowly slide down without moving and is overall not pleasant to the eye or feel, here is the code: https://hatebin.com/gdmpuqgzfk, i'm hoping there is a simple fix to this because i've seen this in games and it looks really well made and i want to know how to do that properly

twin bolt
#

I have a puzzle i'm trying to create that consists of 4 arrows with different rotations, that require the player to interact with each arrow in the right order. How could i go by doing this, while also allowing for me, to be able to customize the order of buttons from the editor?

sage folio
#

well i would say you could use if statements on variables that define the order through the editor, and if the if statements do match up at any point than reset back to the first

#

but i'm not entirely the most educated

sage folio
#

as long as you know basic c# than you should be generally alright, however if you need help with the code i can give you a example

twin bolt
#

Nah i think i got it, thank you.

sage folio
#

yeah no problem

rare basin
#

Queue and serializable class

twin bolt
# sage folio yeah no problem

I got it working, suprisingly on my first try, i just used a list of directions, and checked if the current button, contains the name of the first direction, and if it does it increases the current index in the list, and if not it restarts the index to the beginning.

sage folio
#

thats actually pretty smart, nice job

sage folio
hushed hinge
#

a betatester showed me this and I don't know how to fix the error of the enemy that keeps on repeatedly flipping up

timber tide
#

time to add some logging

hushed hinge
#

for me it's seems to be working, I barely see this

timber tide
#

can you clarify for when it should flip in your logic

pearl lodge
#

Is there a way to save a scriptableObject? I want to be able to have a question and answer as input........ and later be retrieved(even after closing the game).

ashen ferry
#

yea look up save/load json

queen adder
#

what does unity color's declaration look like?

#

they are props right?

hushed hinge
hushed hinge
timber tide
#

well, according to your video there it's not working ^^

#
        if ((_enemyMovement > 0 && _isFlipped) || (_enemyMovement < 0 && !_isFlipped))
        {
            FlipModel();
        }```
#

Could you explain your logic here

ashen ferry
#

that raycast looks a lil short tho if its never grounded it will keep flipping

timber tide
#

Ah, ok I think I understand it. If you're getting help from your teacher you should ask them to leave comments, but what I believe is the idea is that it should flip when it comes to a ledge, but since your enemy is too far above and the raycast is too short like BlinDeex was saying, then it's going to be stuck flipping.

hushed hinge
fossil harness
#

You can try to refactor to be more discrete, I.e.

if (enemyMovement > 0)
{
    SetLookRight();
} 
else if (enemyMovement < 0)
{
    SetLookLeft();
}

(Or some enum for left/right)

#

This should prevent weird logic states

static cedar
#

Yeah that's more preferable. You can have the !is_looking_right condition inside the LookRight function instead.

summer stump
jolly dust
#

For anyone that knows game maker, is it possible to do procedural animation with gml visual?

ashen ferry
#

maybe someone knows opel astra 2008 how do I do clutch replacement

supple wasp
#

How can I make the camera move when touching the screen

pearl lodge
#

In web development there is a thing called a “from” where you fill out some questions and then you submit the form… is there an equivalent for C#/Unity?

sage folio
wintry quarry
#

I don't know, no. You can use Tile map for the world.. not sure why you'd want it for the character

sage folio
mental wren
#

Is there a way to search for all objects with a script attached to them, regardless of script name?

Whether i be searching through a prefab or a scene. Am using either of the search windows in the images featured

cosmic dagger
mental wren
#

I want to find all objects with scripts attached to them regardless of script name

#

if I did t:MyScript it would only find objects with MyScript.cs attached

#

that's not actually useful rn

summer stump
cosmic dagger
mental wren
mental wren
cosmic dagger
#

what are you trying to do?

mental wren
#

I tried t: .cs but it doesnt work

cosmic dagger
#

that's not a script name, that's a file extension . . .

summer stump
mental wren
#

what is a base class

cosmic dagger
#

again, what are you trying to do?

mental wren
#

so do I search for MonoSingleton

cosmic dagger
#

every script attached to a GameObject derives from MonoBehaviour, just use that . . .

mental wren
#

t:MonoBehaviour?

#

oh

#

thanks, that worked

cedar lagoon
#

#include <stdio.h>

void print_time(unsigned long stamp) {
    int seconds = 0;
    int milliseconds = 0;
    int microseconds = 0;
    auto cps = 1000000; // mps_clocks_per_sec();
    unsigned long s = stamp;
    if (cps >= 1000000) {
        // cps is microsecond resolution
        if (s >= 1000000) {
            // stamp exceeds 1000000 microseconds (1000 milliseconds)
            seconds = stamp / 1000000;
            milliseconds = stamp - (seconds * 1000000);
            // stamp_ms must exceed 1000 microseconds
            unsigned long stamp_ms = milliseconds;
            milliseconds = stamp_ms / 1000;
            microseconds = stamp_ms - (milliseconds * 1000);
        } else if (s >= 1000) {
            // stamp exceeds 1000 microseconds
            milliseconds = stamp / 1000;
            microseconds = stamp - (milliseconds * 1000);
        } else {
            // stamp does not exceed 1000 microseconds
            microseconds = stamp;
        }
    } else if (cps >= 1000) {
        // cps is millisecond resolution, do not convert to microseconds
        if (s >= 1000) {
            // stamp exceeds 1000 milliseconds
            seconds = stamp / 1000;
            milliseconds = stamp - (seconds * 1000);
        } else {
            // stamp does not exceed 1000 milliseconds
            milliseconds = stamp;
        }
    } else {
        // cps is in seconds resolution, do not convert to milliseconds
        seconds = stamp;
    }
    printf("Clock:              %lu\n", s);
    printf("Clock seconds:      %d\n", seconds);
    printf("Clock milliseconds: %d\n", milliseconds);
    printf("Clock microseconds: %d\n", microseconds);
}

int main() {
    print_time(3118490); // 3 seconds, 118 milliseconds, 490 microseconds
    printf("c =     %d\n", 3118490);
    printf("cps =   %d\n", 1000000);
    printf("c/cps = %d\n", 3118490/1000000);
    return 0;
}

Anyone know what's wrong?

polar acorn
cosmic dagger
maiden arrow
#

Hey I have a little issue with a 2D platformer where when I make a moving platform the player does not always move smoothly with it. With a vertical one it send the player up a little above the platform when it reaches the top and starts going down. Also with horizontal ones the player moves with the platform but slides a little when it switches directions. I'm using rigidbody.velocity for player movement and platform movement. The way the platform moves is by setting a counter to count up and down depending on which way the block is moving and it'll flip and start moving the other way once the counter goes up or down. That part works fine but how do I get the player to stop sliding on the platform without using a crazy amount of friction because then the player struggles to move on the platform? Also with the vertical moving block how do I get it to not send the player into a little jump at the top?

sage folio
queen adder
#

In a string can I modify the color of specific characters?

rich adder
queen adder
#

thx

bright violet
#

I'm trying to create a JSON by parsing multiple objects in a foreach loop, now, the way I'm doing it is by building a string and then converting it into JSON.

void Saver()
{
    Asset data = new Asset();
    Debug.Log("Saving file as level_" + levelName + "...");
    var sb = new StringBuilder();
    assetScript[] scriptobjects = Object.FindObjectsOfType<assetScript>();
    List<GameObject> objects = new List<GameObject>();
    foreach (assetScript script in scriptobjects)
    {
        objects.Add(script.gameObject);
    }

    foreach (GameObject obj in objects)
    {
        data.objName = obj.name;
        data.posX = obj.transform.position.x; 
        data.posY = obj.transform.position.y;
        data.assetId = obj.GetComponent<assetScript>().assetId;
        string json = JsonUtility.ToJson(data, true);

        Debug.Log(json.ToString());
        sb.AppendLine(json);
        
    }
    File.WriteAllText(Application.persistentDataPath + $"/level_{levelName}.json", sb.ToString());
}```
This is fine however I need these objects to be in an array for loading purposes, I tried making a list of objects but the output file is always {} and i don't get why.
#

this is the code with the list:

void Saver()
{
    List<Asset> dataList = new List<Asset>(); 
    assetScript[] scriptobjects = Object.FindObjectsOfType<assetScript>();
    List<GameObject> objects = new List<GameObject>();
    foreach (assetScript script in scriptobjects)
    {
        objects.Add(script.gameObject);
    }

    foreach (GameObject obj in objects)
    {
        Asset data = new Asset(); 
        data.objName = obj.name;
        data.posX = obj.transform.position.x;
        data.posY = obj.transform.position.y;
        data.assetId = obj.GetComponent<assetScript>().assetId;
        dataList.Add(data);
    }

    string json = JsonUtility.ToJson(dataList.ToArray(), true);

    Debug.Log(json);

    File.WriteAllText(Application.persistentDataPath + $"/level_{levelName}.json", json);
}```
tiny terrace
#

hello, how can I instantiate an array of gameobjects in a straight line with equal spacing with each other?
I want to use this for my game's status effect indicator. And is there a way for these game objects to align themselves when the first status expires like this:
X X X X - 4 status indicators
X X X - the first status in the left has expired

silent valley
#

Hi. Is there any code that can keep my camera locked for lets say 5 seconds? I always start the game looking at the floor or wherever because i'm holding my mouse.

tiny terrace
static bay
tiny terrace
#

alright thank you

static bay
#

deleting or disabling one of the children should also cause it to reorder

#

so you should get that "shift over" behaviou you wanted

obsidian jewel
#

i want to make some paper just visible in specify zone. i start use sprite mask but i already use sprite mask for paper. Is there have another way i can do ?

silent valley
#

I want my camera to stay stationary for 3 seconds when the game starts. I've tried this void start and many other things. it doesnt work, any help?

keen dew
#
if(Time.time < 3) {
  return;
}

at the start of the method

#

also don't multiply mouse input by deltatime

silent valley
#

fml I've mad eit so my mouse deactivates after 3 seconds xD

#

You are a saviour. I had a dumb moment. spent hours on this. it works flawlessly. Thank you so much. Also you mentioned not to multiply mouse input by deltatime. How comes?

fickle karma
#

Hi. In the tutorial to get my unity project unto github they use a new file and can easily match the folder directions. However im using an existing project, and i cant seem to change the folder for this project to match the github folder.

I tried save as inside github doesnt work (doesnt allow a save)
I tried manually dragging the project files into github didnt work

slender nymph
silent valley
# keen dew ```cs if(Time.time < 3) { return; } ``` at the start of the method

Sorry to bother you again. I have my main menu scene as index 0 and my first level as index 1. the 3 second timer starts while I'm on the menu. So if im on the menu for 4 seconds. the timer has already passed. I didnt know that the other scenes are active. Do you know a way top deactivate a scene until it's active?

fickle karma
slender nymph
#

just create the repo right inside the project folder

#

or drag all of the files created by git in whatever folder you created the repo in into your project folder. then you can point your gui client (probably github desktop if i had to guess) to that folder

#

it's not a "bullshit system" just because you don't know how to follow directions

feral notch
#

Does anybody know why this setup introduces a delay when moving from "Midair" to "Idle"?

#

But when using this setup there is no such delay?

slender nymph
feral notch
#

sry

maiden jay
#

I'm a little confused about this Graph class. It says its type is Location but you can use it with whatever other type? What is this called? I've been trying to google what this is but I can't really find anything. Type override? I had assumed you needed to make it generic to do something like this. The <Location> is declaring which type can be overriden I guess?

slender nymph
#

I'm pretty sure this is just a generic class where the generic type parameter is called Location. it's not actually using a type called Location here, it's just the name you've given to the generic type parameter

#

replace all instances of the word Location in that class with T and it will make more sense to you as to what is actually happening

maiden jay
#

Yeah as T it makes more sense to me but there's also a struct for Location so idk

#

I guess it still works that way

slender nymph
#

right but that struct is 100% irrelevant to your Graph class. you just happened to give the generic type parameter the same name as the struct

#

the reason i suggested replacing Location with T in Graph was because it is functionally the same exact thing. there is no difference except in the name of your generic type parameter. T is just the standard name used for it much like how i is the standard loop iterator name. you can give it whatever name you want, in this case you've given it the name Location, and it doesn't change what it is or what it does, just what it is called

#
for(int i = 0; i < 3; i++)
  Debug.Log(i);

for(int Location = 0; Location < 3; Location++)
  Debug.Log(Location);

these loops are functionally identical. the only difference is that i called the second loop's variable Location instead of i. that doesn't mean it has anything to do with your Location struct

maiden jay
#

Yeah I guess.

wintry hull
#

Hello I was trying to build my game but this error message kept apearing

slender nymph
#

you can't use the UnityEditor namespace in a build

wintry hull
#

how do you fix that

slender nymph
#

editor code should be wrapped in conditional compile directives or be put into a folder called Editor

wintry hull
#

Im not really sure what that means

slender nymph
#

why are you even accessing the Build class namespace in a PlayerMovement script? 🤔

lean basin
#

hello, I have 2 Transform object. I wanted to set one object's rotation.y so that the first transform is facing another transform.
How do I do that?

What I'm doing now is
deltaTransform = transform1.position-transform2.position
and then setting the rotation like this
transform1.rotation.y = Mathf.atan2(deltaPosition.z,deltaPositionx)
transform1.rotation = Vector3(0f,Mathf.atan2(deltaPosition.z,deltaPositionx),0f)

is this incorrect? it doesn't seem to do what I wanted.

wintry hull
#

I really dont know

slender nymph
#

so remove it

slender nymph
wintry hull
#

thank you so much boxfriend

lean basin
slender nymph
#

well Atan2 does return the angle in radians. but you don't even need to use it. just use Quaternion.LookRotation to get the desired rotation

lean basin
#

what the fuck is a quaternion, apologize for my language.

slender nymph
burnt vapor
#

Unity has a lot of build in inheritable classes that make it easier to do this

#

Generally your editor code ends up in a seperate file inside an Editor folder. Unity will automatically strip these files when you make a build.

#

Otherwise, use conditional compilation as boxfriend mentioned, which means Unity will ignore the editor specific code inside the conditional

wintry quarry
#

That's all that matters

wet anvil
#

Hello, I'm very new to programming. And I was wondering if there was an Unity in-build way to verify that someone has drew correctly on a pre-set segment ? Maybe, a kind of trigger or whatever ? I don't even know how to put my question, sorry if I'm being confusing.

Like in those learning app where u have to draw a symbol ans it checks if you have written it correctly. Thanks you

#

Like verifying that each segment has been drew on the right place ? Some kind of trigger that i'm not aware of maybe ?

frosty hound
#

There is no built in way, no

#

Maybe check the asset store?

wet anvil
frosty hound
#

Where people make custom tools, assets, etc. See if someone made a game template or something that includes this feature.

wet anvil
#

Where do I find such store ?

#

Is there like an official place for that?

wintry quarry
#

Yes, the asset store

frosty hound
#

Yes, you can google the Unity asset store for the link

wet anvil
#

The thing is I don't even know how to formulate my question ahah

#

In a simple and programming-like sentence yk

wintry quarry
#

Glyph recognition

#

Handwriting to text

#

Stuff like that

wet anvil
#

Kk tks yall

verbal dome
#

Was gonna say scribble detection but that sounds more accurate^

frail hound
#

Anyone here know how to get a 2d sprite to point at the mouse? Because I tried but I kept pointing in 3d and disappearing.

slender nymph
#

get direction from sprite to mouse, assign either its transform.up or transform.right to that direction depending on the direction the sprite faces when not rotated

#

don't use transform.LookAt for 2d objects

frail hound
slender nymph
#

no, did you even read what i said?

frail hound
slender nymph
#

please learn to read

frail hound
slender nymph
#

assign either its transform.up or transform.right

#

again, learn to read

frail hound
slender nymph
#

transform.up is the direction of the objects' Y axis. when the object is not rotated at all then yes it will be 0,1,0

frail hound
slender nymph
#

you get the position from its transform

vernal thorn
#

How can i make a custom SpawnPoint

using UnityEngine;

public class ObstSpawner : MonoBehaviour
{
    public GameObject ObstPrefab;
    public float SpawnSchnelligkeit;  

    private void Start()
    {
        InvokeRepeating("SpawnObst", 0f, SpawnSchnelligkeit);
    }

    private void SpawnObst()
    {
        Instantiate(ObstPrefab, transform.position, Quaternion.identity);
    }
}
#

?

#

like a object where it spawns

#

instead of the object whit the script

slender nymph
#

instead of using transform.position (which is this object's position) as the position to spawn it at, you can create an empty gameobject at the location you want it to spawn and use that object's transform.position. or you can just create a Vector3 variable and use that

vernal thorn
#

thanks

frail hound
frozen dagger
#

why when i added line 52 and function 'private void OnApplicationFocus(bool focus)' movement stoped working and character started to fly...

keen dew
#

Your file doesn't have line numbers. Use a paste site: !code 👇

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

jolly dust
#

How do you make it so you stay in place and everything else moves?

polar acorn
quick pollen
#

My assumption is that it break because I use time.DeltaTime and because framerate isn't constant, it sometimes leaves small errors like that

#

how could I make it, so it's not frame dependant?

tawdry rock
#

Quick question: If i instantiate something as a child but the Parent has a 1.5 scale ratio how do i instantiate my object to keep its own 1 scale ratio?

ivory bobcat
tawdry rock
polar acorn
charred tiger
#

Hey I'm trying to create a unity game but I honestly don't know how to start the game

ivory bobcat
quick pollen
#

first come up with an idea

#

and then try to make it

polar acorn
charred tiger
quick pollen
#

I was thinking perhaps making it depend on distance from a source point?

verbal dome
quick pollen
#

and it's even more appearant when the projectile has a high speed and emission rate

verbal dome
#

Is it using emission over distance?

quick pollen
#

theyre not particles btw

#

theyre gameobjects

verbal dome
#

Ah. Well, you need to show the code that emits them

quick pollen
#

sure

#
public class SubEmitter : MonoBehaviour
{
    [SerializeField] GameObject[] projectiles;
    public float atkCoolDownCT;
    [SerializeField] private float fireDelay;
    private int currentProj = 0;
    private float atkCoolDown;
    private float stunTime;
    private void OnEnable()
    {
        atkCoolDown = atkCoolDownCT + fireDelay;
    }

    void Update()
    {
        stunTime = EnemyStagger.StaggerInstance.stunDuration;

        if (stunTime > 0f) atkCoolDown = atkCoolDownCT + fireDelay;

        if (atkCoolDown <= 0f)
        {
            atkCoolDown = atkCoolDownCT;
            FireProjectile(currentProj);
            currentProj++;
        }
        else
            atkCoolDown -= Time.deltaTime;

        if (currentProj > projectiles.Length - 1) currentProj = 0;
    }

    private void FireProjectile(int index)
    {
        GameObject projectile;
        projectile = ProjectilePools.ObjectPoolInstance.GetPooledObject(projectiles[index]);
        ProjectileHandler projHandler = projectile.GetComponent<ProjectileHandler>();
        if (projectile != null)
        {
            projectile.SetActive(true);
            projectile.transform.position = this.transform.position;
            projHandler.SetMoveDelay(GetComponent<ProjectileHandler>().LifeTime);
        }
    }
}```
#

its a pretty basic implementation

verbal dome
quick pollen
#

I also have a list of projectiles instead of one so I can make it so it emits proj1, then proj2, etc

quick pollen
verbal dome
#

Yeah but im suggesting doing the atkCooldown -= deltatime first, them checking if it is <= 0

quick pollen
#

hmm

#

idk what that'd change

#

but I can try

#

oh yeah, I also do atkCoolDown -= Time.deltaTime inside of the else statement

charred tiger
verbal dome
quick pollen
#

@verbal dome tbh for the time being I "fixed" the issue by increasing the projectile size, so its much less appearant if there are small issues

#

but ill try to see if what you said really fixed it

verbal dome
#

Its a guess

quick pollen
#

it didnt fix

#

there are still inconsistencies

#

I think the main issue has to be Time.deltaTime

#

but I'm not sure how to make the emission of the smaller projectiles not framerate based

verbal dome
#

You probably have to do some interpolation math to make them spawn on consistently spaced position instead of the current position

#

Im not great at explaining it

quick pollen
#

because in extreme examples, if there's 1 second between the current frame and the frame before, then it not only moves more because of the movement using deltaTime too, but also the emission

quick pollen
#

it kind of reminds me of the hit detection issue

#

where if a gameobject moves too fast, and the framerate isn't high enough, then it has the chance of completely missing collision with an object that was in it's path, because there wasnt a frame that captured the collision

#

so smth that people did is draw raycasts between where the object is, and where it was

#

and using that to detect collision

tawdry rock
#

Seems like parent constraint component only have position/rotation. i found scale constraint component but if i freeze my scale still gonne scale according to parent.. idk what the deal with them.
i also tried :
GameObject go = Instantiate(...); go.transform.localScale = new Vector3 (1,1,1);

quick pollen
quick pollen
#

kind of cheaty though

#

i wouldnt be surprised if that caused problems later

tawdry rock
#

so maybe it should be better to resize my model in Blender rather than set its scale in unity... for now i don't see the problem, i only use it for loots to spawn in containers. its a extra line of code and might gets on the performance on a larger scale but thats why loading screens there for 😄

olive lintel
#

hey guys sorry for the strange question but why can I not use Random.Range() while using System in my monobehaviour?

verbal dome
languid spire
olive lintel
wheat cypress
#
    public void quit() => Application.Quit();

Hello, i made a button to quit my game but when i click on it nothing happen, any idea please ?

languid spire
#

Application.Quit only works in a build

wheat cypress
#

Ah, i'll try with building ver then, thanks

#

Works, thanks

quick pollen
quick pollen
silent valley
#

I made a raycast for interactables and now I'm wanting to use a second layer for triggers but struggling to have them together. plz help

polar acorn
silent valley
#

Yes. I think that would achieve the same thing. probably a better way to do it. I have a feeling my "else" part is the issue

polar acorn
#

If your first ray hits something, and that thing has no interactable, you cast a second ray with the same parameters

silent valley
#

so I should get a message in my console right? My second one is for triggers. make things happen etc

silent valley
#

Anything with the "interactable" layer

polar acorn
silent valley
#

a cube with the "LayerTrigger" layer

polar acorn
silent valley
#

yes

vernal thorn
#

Is there a way too comapc this in one app?

polar acorn
polar acorn
vernal thorn
#

as a icon

silent valley
#

Are you talking about this?

polar acorn
serene geyser
#

do someone know how to get rid of this message in visual studio code?

polar acorn
slender nymph
#

That's code lens, but why would you want to disable features that make it easier to debug and to understand how your code works and finding where things are used/not used

silent valley
polar acorn
#

So I'm asking what is the object in the Interactable layer that doesn't have the Interactable component that you are looking for

serene geyser
#

What do it mean when the vscode file is "untracked" and is having a green glow

polar acorn
serene geyser
#

Can you remove those messages even tough it's not been added to the git or is modified?

silent valley
#

@polar acorn I changed the position of my collision and it works. it registers me hitting the collision layer.

polar acorn
# silent valley

This is no longer checking for if the first ray hits anything before casting the second

silent valley
#

Interactable interactable = hitInfo.collider.GetComponent<Interactable>();

#

This line right?

#

I noticed that and literally face palmed

rich adder
silent valley
silent valley
#

Whats the cause of a lag spike when colliding with a trigger?

silent valley
jagged gulch
#

Working on scripting an animation for my weapon in my game, but having issues with the animator rn. I have it setup so it has a basic

  Turn Bool to True and start animation
When animation is done
  Turn off bool and transition back into idle state

kind of script. I had the transitions setup properly and debugged to get the bool when starting the scene. Everything checked out right but the animation wouldn't start. I rewinded a bit and took it step by step and am now just trying to get the animation to play when the scene starts. However, even that isnt working

#

not sure whats wrong and why the animation wont just start playing as soon as the scene starts. I have the animator and animation properly setup on the weapon's object as well and have the firing animation as the default state for debugging.

toxic pine
#

how do i fix the curser being that weird square

wintry quarry
toxic pine
dim fossil
#

im trying to display the y coordinates of an object (2D) but cant find anything online. does anyone know how to do this?

dim fossil
#

just on some random text in-game

wintry quarry
#

use ui text

#

simple

dim fossil
#

yea

#

im trying

wintry quarry
#

whats the issue

dim fossil
#

i dont know how to do it

wintry quarry
#

what part dont you know how to do

#

where are you getting stuck

#

what hve you done so far

dim fossil
#

i dont know how to track the object

queen adder
wintry quarry
#

just reference it

dim fossil
wintry quarry
#

public Transform theObject;

#

then theObject.position.y

queen adder
#

Debug.Log(theObject.position.y);

dim fossil
charred tiger
polar acorn
#

Like what

charred tiger
#

Like an intro when I enter the game

rich adder
#

use video player component or animate in unity with Timeline

charred tiger
#

Ok

worn tree
#

Hello! Im making a game where the user saves their name and level in an input text field, and their stats are displayed in the text for the user to see. currently when the app closes all of the data goes away. I want there to be multiple saves whenever a user hits the save character button. I made a character class, but unity confuses me. Do i make a prefab named character and put my script on it? Or do i just make an instance of the character object call it profileOne? How should i go about saving the players name and level from the text and then display it in the text when a button is clicked from a specific character game object?

summer stump
worn tree
#

okay awesome! ill check the unity docs! 😄

summer stump
#

There is some way to use SerializedObject too, but it doesn't work by default and I haven't done it

worn tree
#

okay! Thank you for your guidance!! ill remember that if this doesnt go well for me!

primal tree
#

I've a big block of JSON which I'm looking to convert into URL Params in order to pass it to a Apps Script / Google Sheet. Does anybody know if this is a good way to send several pages of dictionaries? Anybody know of a good way to convert JSON into URL Params?

wintry quarry
#

can't you just directly send the json blob as the HTTP body?

zealous oxide
#

hey friends, i'd like to add a collectable item to my platformer that shrinks the players size. i'm guessing i should just concentrate on shrinking the Y scale of the transform? (as opposed to the Y size of the box collider2D). i've tried it with this but its not working

slender nymph
#

in what way is it not working?

zealous oxide
#

hey boxfriend! its not changing the transform scale

unkempt locust
slender nymph
zealous oxide
unkempt locust
zealous oxide
#

ok that worked, thank you!

#

now i guess i need to work out some logarithmic formula so the transform doesnt go beyond a certain value so the character can never shrink into nothingness

slender nymph
#

why not just clamp the scale? at a certain point it won't really make much sense to actually reduce its size anymore

zealous oxide
rich adder
#

collider issue probably, lets see the player inspector with collider selected in playmode

slender nymph
#

getting caught on the edges of tiles is a known issue with the 2d physics engine that unity uses (box2d). there are a couple of steps you can take to try and solve this:

  1. set the rigidbody's collision detection to continuous
  2. use a round bottom collider for your player instead of one with a flat bottom
  3. use a composite collider for the tilemap
slender nymph
rich adder
#

I bet 3 would also fix it with square collider, maybe with no friction material helps too

slender nymph
#

yeah composite collider is probably the most efficient fix since that would treat the entire tilemap collider as one big collider instead of individual tiles. and it works with flat bottomed colliders (at least in the limited testing i've done, i typically still use capsules or circles for my players)

pearl lodge
#

Can I create/delete a script with code?

slender nymph
#

depends, for what purpose?

valid finch
#

why would my animation not reset to idle when I am not moving any direction

slender nymph
#

show your code where you set the parameters back to 0,0

valid finch
#

^^^ doh

#

So simple.. Just figured since there wasn't input it would go back to zero.. but yeah, you are right

meager ermine
#

how would i go about adding a background that's actually behind everything

wintry quarry
valid finch
#

Send a screen shot.

#

Order in Layer typically

rancid tinsel
#

how do i detect if an the object with the script on it is being pressed? im trying to do OnMouseOver() but that seems to do nothing

meager ermine
wintry quarry
rancid tinsel
#

been a while since i played around with unity so im definitely just being stupid

wintry quarry
#

and just put an Image component across the whole thing

wintry quarry
#

whjy don't you just use OnMouseDown?

#

this is overcomplicated

rancid tinsel
valid finch
#

@meager ermine ^good option. If you are using sprites, you can just go to the inspector of the background and go to the sprite renderer within and change the order in layer

wintry quarry
#

you can still do the timer thing

#

but you don't need the extra bool

rancid tinsel
meager ermine
#

@wintry quarry @valid finch thanks y'all that helped

rancid tinsel
#

and im pretty sure i used it just like the example on the documentation

meager ermine
worn tree
wintry quarry
#

and the if statement

#

put a Debug.Log statement at the beiginning of OnMouseDown

#

before any conditions

#

just start with making sure that works on its own

rancid tinsel
polar acorn
rancid tinsel
wintry quarry
rancid tinsel
#

ahhh

#

okay makes sense

wintry quarry
rancid tinsel
#

i did but i skipped the collider part 😭

wintry quarry
#

like 80% of the sentences on that page mention colliders 🤔

rancid tinsel
#

added a collider and it works like a charm

#

why isnt the bool needed though?

#

the idea is to prevent the player from clicking the button again until the animation plays out

wintry quarry
#

Actually the if (Input.GetKeyDown(KeyCode.Mouse0) is not needed

#

why's that there

#

we're already in OnMouseDown

rancid tinsel
#

yeah that was there before my bad

wintry quarry
#

pressed is just a poorly named variable

#

it's not about whether it's pressed

#

it's about whether the timer is up

rancid tinsel
#

pressed makes sense to me though, since the animation is of the button being pressed

wary delta
#

clickDelay

rancid tinsel
#

this is what I ended with and it works perfectly now

rich adder
#

Your animator OnGround is not properly configured

wary delta
#

That wasn't for you, I was just chiming in on a variable name

rich adder
#

huh ? sometimes you're mid-air and OnGround is checked

#

you should show your setup on how you also call jump

#

How do you set Animator OnGround

#

show code

polar acorn
#

!code

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

wary delta
rich adder
#

put this in your code

private void OnDrawGizmos()
    {
        Gizmos.DrawSphere(groundCheck.position, groundCheckRadius);
    }```
#

hit play, make sure Gizmos is on in Gameview/scenecview

#

it says Gizmo on the Game view, to the right

#

hit play and screenshot game

#

so you didn't enable it..

#

click it

#

so it turns light gray

#

if you dont see a gizmo after enabled then your Groundcheck is nowhere on sight

#

where is your Groundcheck transform

#

nvm that

#

look at your groundcheck

#

that white sphere

#

Physics2D.OverlapCircle

#

thats how big it is

#

when its true

#

quite a bit

#

the variable you have for it

#

groundCheckRadius

#

put ground check a bit closer to your knee height

#

so it almost lines up to your collider bottom half

#

make it about same radius as ur collider but slightly bigger

solid timber
#

Hey, if you are ***constantly ***changing a players gravity, with Rigidbody2d.gravityScale, does it matter if it is in Update() or FixedUpdate()?

rich adder
#

like his leg height lol i said knee, that aint his knee and reduce radius

rich adder
#

dont worry about animation rn

#

worry about fixing your huge groundcheck for code

#

something like this

#

maybe slightly more down but you get the idea now

#

animation wise you would still need to make the Transition timing smaller so you dont have 2 clips repeating

#

but it should fix your jumping / animation timing and wont be able to jump midair

#

you really don't see why?

#

what have we been doing this whole time..

#

you're checking for grounded bool to jump , are you with me so far?

#

the size of that check is as big as that big gray sphere yes?

#

as long as the gray is touching a collider Grounded in layer

#

is Grounded

#

and you can jump

summer stump
rich adder
#

thats still too big

#

you wil be grounded if your sides are touching a platform with Grounded layer

#

youd be able to jump even if your head is touching that platform

spiral glen
#
        print("hit something");
        if (hitObject.gameObject.tag == "Deleter" ) {
            print("hit " + hitObject);
            Destroy(gameObject);
        }
    }```
am I doing something wrong here, my walls have the deleter class.
rich adder
summer stump
#

Why do you still have it so huge?

rich adder
#

time for some glasses

summer stump
#

The circle is bigger. That is the difference.

A LOT bigger. Your circle is taller than your character!!

rich adder
#

time for a thicker pair

summer stump
rich adder
#

pay attention to the variables you write

#

lol its literally in the name

rich adder
#

in the inspector of the script?

summer stump
spiral glen
rich adder
#

you're using wrong method

spiral glen
#

oh

rich adder
#

OnTriggerEnter2D

#

make sure u have at least 1 rigidbody

spiral glen
#

wdym atleast 1

rich adder
#

close but still toobig and too far down

rich adder
#

bruh..

#

are you fr?

summer stump
#

It has to extend past the green circle

rich adder
summer stump
#

The green circle is the collider, and it won't move down further than that

spiral glen
#

It's giving me an error saying,
"Script error: OnTriggerEnter2D
This message parameter has to be of type: Collider2D
The message will be ignored."

summer stump
summer stump
#

Sure, that is good enough probably

rich adder
#

id still lift it up a bit but fine

#

did you fix the transition / repeating animation issue?

spiral glen
#

Is there a way to make it so a collider wont interact with another specific collider (like wont move it around or anything)

rich adder
#

Physics2D.IgnoreCollision or use Layer-Based collision to ignore them

#

or triggers

spiral glen
#

Layer based collision being that since object x isn't on the same layer as y it can't interract?

rich adder
#

they all interact by default ofc

#

for 2D this is under Physics2D category

spiral glen
#

I did it, thanks

tame mist
#

Hello, I have some code setup to tell me the position of an arrow when the player is able to hit it and where the location on the x position it is when the button is pressed. For some reason in the unity editor the position on the arrow looks correct but the Debug.Log statement is kind of off and it triggers the "ok hit" instead of the "perfect hit" code when it's in the perfect zone.
I have no idea why it's doing this.

        {
            if (canBePressed)
            {
                if (Mathf.Abs(transform.position.x) > -1064)
                {
                    Debug.Log("ok hit");
                    Debug.Log("ok " + Mathf.Abs(transform.position.x));
                } 
                else if (Mathf.Abs(transform.position.x) < -1124)
                {
                    Debug.Log("ok hit");
                    Debug.Log("ok " + Mathf.Abs(transform.position.x));
                }
                else
                {
                    Debug.Log("perfect hit");
                    Debug.Log("perfect " + Mathf.Abs(transform.position.x));
                }
            }
        }
    }```
nocturne parcel
#

Probably dumb question, but how do I access the index of a list that is inside a 2 for loop?

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                Vector3Int position = new Vector3Int(x, y);

                float islandValue = heightMap[x,y] - squareFalloff[x,y];

                if (islandValue < 0.4f)
                {
                    tilemap.SetTile(position, water); 
                    waterTiles.Add(tilemap.GetTile<WaterTile>(position))
                }```
I want to get the tile that I just added into the list. I could use `tilemap.GetTile` again, but I'll have to access the list anyway later on also in a double loop.
polar acorn
nocturne parcel
#

ty, i'll try it out

tame mist
nocturne parcel
#

Until eventually going out of bounds

polar acorn
nocturne parcel
#

Do I need to explicitly call RefreshTile or is it already called by the engine when I use SetTile?

pseudo frigate
#

i have a 3d top down game that plays kind of like 2d 1942, i have WASD movement set up to move the character around without rotating it at all, i want the rotation to be based on where the mouse cursor is. how can i accomplish that? what ive tried so far looks janky and way off. im only looking to rotate the players Z axis and point where the mouse is

#
  float camToPlayerDist = Vector3.Distance(transform.position, Camera.main.transform.position);

  Vector2 mouseWorldPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, camToPlayerDist));

  Vector2 direction = mouseWorldPosition - (Vector2)transform.position;

  float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

  transform.rotation = Quaternion.Euler(0, 0, angle-90);

this kinda works but looks a little off

ivory bobcat
pseudo frigate
#

ill try that solution, thanks

ivory bobcat
#

Else if you need the character to immediately turn just assign forward to the direction.

pearl lodge
# slender nymph depends, for what purpose?

I want have an input field for a question and answer. Then I want to save it as a scriptableObject.

I want to be able to close the application and reopen it and have the questions and answer show up.

Like a “test yourself study guide” game

nocturne parcel
#

So, I'm tyring to get the neighbours of a tile, but I'm getting an out of bounds exception. Anyone knows what is wrong with my array?
https://pastebin.com/QLSR5A40

slender nymph
#

You just need to serialize the strings and save them to disk

pearl lodge
#

Json?

nocturne parcel
rocky epoch
#

I have a problem with my player controller where when i press "R" to roll, the animation is delayed a bit
it only happens sometimes, and a example of it is at 0:02
does anyone have a solution?
*i can show you the animation controller for the player and the rest of the script
https://pastebin.com/mz6CfEke

frail hound
#

does anyone know how to get the position of a item when the script isent attached to it?

rich adder
#

or make a direct reference to transform

frail hound
rich adder
#

Debug.Log(myItem.position);

frail hound
#

oh ok

#

ill try it out in a bit

queen adder
#

is there a Resources.Load thingy for editor that can search anything in project folders even not in a Resources folder?

pseudo frigate
#
            Ray cameraRay = cam.ScreenPointToRay(Input.mousePosition);
            Plane ground = new Plane(Vector3.up, Vector3.zero);
            float rayLength;

            if (ground.Raycast(cameraRay, out rayLength))
            {
                Vector3 pointToLook = cameraRay.GetPoint(rayLength);
                Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue);
                partToRotate.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
            }

what do i need to add/change here so that the part to rotate looks straight ahead and only rotates on one axis? right now it's looking at the floor which i dont want. the X in the image is about where i have my mouse cursor

#

is more what im going for

hollow kraken
#

Anyone know how i could apply inertia to a 2d sprite without using rigid body components?

#

I have a ship that takes horizontal and vertical input but i need it to slowly come to a stop once the user lets go of one of those input

rose galleon
cosmic dagger
ashen ferry
#

cuz ur dashPower is always same atleast in that script

rose galleon
ashen ferry
#

idk the context when u want to dash left u could invert dashPower

rose galleon
#

ig i do that with the sprite for left and right

#

i could try for dashing

swift crag
#

probably to the Y position of the robot's head

swift crag
#

you have transform.position.y there, but is that the right transform?

#

if it's the robot's transform, that's probably between its feet

#

partToRotate's y position may or may not be appropriate

rose galleon
#

also, why isnt Drop showing up?

ashen ferry
rose galleon
swift crag
#

It won't recompile if you have any errors.

rose galleon
#

ohhh

#

true

#

the errors

rose galleon
#

ty so much

#

it is working now

elfin eagle
#

hey so im trying to hit the slime (which has a collider2d attached) which does hit, but if I stay in the same place and try to hit again it doesn't go through and if I move back outside the slime collider and go back in then it registers the hit. how can I make it that the hit will register in the same place without having to move back?

timber tide
#

Show code

#

and probably clarify how you're hitting the slime

elfin eagle
#

Here is the sword animation hitbox

timber tide
#

Ah, so you're just colliding with them

elfin eagle
#

then here is the sword hitbox true or false depending on when the player hits the key

timber tide
#

I believe OnTriggerEnter won't be called again until the colldiers that collided have been disjoined

elfin eagle
#

ah ok is there a different method i should be using?

timber tide
#

You have this, but youll want to set up a timer/cooldown so you won't call every frame

#

Well, it will be called regardless, but you'll want to limit the logic contained else you'll instant kill your enemies ;)

elfin eagle
#

alright thanks, is it defaulted to call on every frame?

timber tide
#

I think it's based on fixedupdate? You can also just cast yourself using overlapsphere/overlapcircle and gauge the logic in an update loop

elfin eagle
#

okay thanks for the help

timber tide
#

Ye np

teal sleet
#

I'm in need of a hand if possible please.

I started using the Inventory system by Devion Games last year.
Took a break from Unity. It used to work but for some reason one button doesn't seem to function within the Unity UI now.

Every time I click it I get this error. Is a package missing that's clashing with the old code?

NullReferenceException: Object reference not set to an instance of an object DevionGames.InventorySystem.VisibleItemsEditor.ShowWindow (System.String title, UnityEditor.SerializedProperty elements) (at Assets/Devion Games/Inventory System/Scripts/Editor/VisibleItemsEditor.cs:34) DevionGames.InventorySystem.EquipmentHandlerInspector.OnInspectorGUI () (at Assets/Devion Games/Inventory System/Scripts/Editor/Inspectors/EquipmentHandlerInspector.cs:92) UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <66e151436a4945b595f4b482260aa84d>:0) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

#

Basically the inventory system by Devion games scripts interfaces into Unity for ease of access references things in your database

#

Usually I'd click either button and get a pop-out.
Unfortunately the developer hasnt been active in a long time.

calm coral
#

Hey, is anyone familiar with Physics Raycaster component? I have no idea what that is and I couldn't find anything in the Unity's documentation

calm coral
calm coral
teal sleet
north kiln
#

You have something null at VisibleItemsEditor.cs:34

#

it's unrelated to UGUI events

teal sleet
#

Ok thank you, apologies for DMing.

teal sleet
pseudo frigate
#
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
pointToLook.y = partToRotate.position.y;
partToRotate.LookAt(new Vector3(pointToLook.x, pointToLook.y, pointToLook.z));

im using this code above to rotate my robots upper half turret to follow the mouse, right now it moves instantly but id like it to take time to rotate based on a rotation speed. i tried doing something like this but it wasnt working right, can anyone please point out my mistake? thanks

Quaternion turretRotation = Quaternion.LookRotation(pointToLook.normalized, Vector3.up);

partToRotate.localRotation = Quaternion.RotateTowards(partToRotate.localRotation, turretRotation, turretRotationSpeed * Time.deltaTime);
timber tide
#

Maybe mixing local and world coordinates up if you're using mouse coordinates? Little rusty on this stuff so that would be my guess.

#

Otherwise looks fine to me

pseudo frigate
#

i tried using rotation and localrotation and neither worked correctly =/

ivory bobcat
#

The direction would be equal to the point you're wanting to look at minus your current position, normalized.

atomic bison
#

what is the best system to save position of items etc between scenes in android/ios? a json utility? binary save? do you suggest me to use any plugin? or its more easy? scriptable can save data but will be reset when app is closed no when a new game started really?

round scaffold
#

guh

vague oyster
#

I cant find Device Simulator under Preferences, even tho i installed it in packet manager?

keen dew
#

Not a code question, but it's in project settings, not preferences

burnt vapor
#

Then just store it in memory in a component manager

#

If you need to persist between sessions, then you would start looking into storing the data as json or other formats (EDIT: and please do not use JSONUtility for this)

fickle karma
#

Hello guys. Please help me out. I made a scenemanagerscript to switch scenes. Gave the component to the button and the canvas the button is on and it worked. After doing some changes to the design, apparently the functionality doesnt work anymore. I cant find the issue

fossil drum
fickle karma
#

Yes its better to let you guide me to tell you what you need to know to help me 😄

burnt vapor
#

Share any errors that your Unity console might display when this functionality fails.

fickle karma
#

No errors ill add the debug code to the script now

burnt vapor
#

Otherwise just share the script and possible screenshot the component shown in the editor inspector

fickle karma
#

OK. I didnt change the script and it worked earlier. I dont know how to add the debug code, so ill just do that. In visual studio i can also press debug, is that sufficient?

burnt vapor
#

As Micro Jackson mentioned, place a Debug.Log down. This can help a lot with understanding the actual issue. Place it at the start of LoadScene, and have it print out SceneName. See if this logs, and also logs the right scene.

fickle karma
#

sorry im new to this, you gotta tell me exactly how to write it

#

I get this error in console. Can it be because i changed the pixels that i cant press buttons?

young warren
#

Or go through the beginner scripting course in Unity Learn

#

It's pinned in this channel

fickle karma
stiff birch
eternal falconBOT
#

🧑‍🏫 Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

burnt vapor
#

Because you seem to have no idea how the context is supposed to be written

#

I suggest you learn the c# syntax before trying Unity. Otherwise you're learning two topics when you should have learned c# first.

fickle karma
#

I dont have the luxury to do that, but yeah

fossil drum
stiff birch
#

Why don't you have the luxury to learn how to code 1st ?

#

I mean, it's not a luxury, it's a necessity

burnt vapor
junior fern
#

Sigh first week in Unity and I am already having a problem getting my sphere to follow my mouse.. Is this where I ask for help ? 😦

fickle karma
#

Im at a university where we learn both at once. Ill look into a lot of c# in my freetime thank you for the suggestion.
I added the debug.log, but in the console i only get this

slender nymph
slender nymph
fickle karma
slender nymph
#

screenshot your entire console window

junior fern
slender nymph
#

show your code

fickle karma
slender nymph
#

and you have clicked the button?

fickle karma
#

And yes it used to work until i copied the button 3 more times, and changed the dimensions

#

i cant click it

#

in game nothing happens now

slender nymph
#

wdym you can't click it?

languid spire
fickle karma
#

i click and nothing happens, its like the button isnt there

slender nymph
slender nymph
#

select the event system in the hierarchy and pay attention to its preview window at the bottom of the inspector when clicking things in your scene during play mode. if it is not detecting your button when you click it, then something is probably blocking the button

languid spire
#

he's got 3 buttons outside of the canvas

slender nymph
#

ah don't spoil it

languid spire
#

which button is subscribed

fickle karma
#

Yes i have not finished those buttons yet. i only care about this button atm

slender nymph
void jacinth
#

Hello! I have written this code that detects if the Line of sight of an enemy collides with a player. If it does, I tell the enemy to move towards the position of the collision.

private void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.tag == "Player") {
            enemyScript.playerFollower(collider.transform);
        }
    }

The problem is it only checks the collision once, and goes to the point of collision, but I want it to repeatedly check if the player is inside the line of sight and move towards it.
This probably means I have to approach it differently, but I can't think of a way to do it.
Any help is appreciated.

slender nymph
#

couple notes:

  1. use the CompareTag method rather than string equality to check tags. it is not only a (very small) performance gain, but will throw relevant errors when a tag doesn't exist instead of just failing silently
  2. use a physics query like a Raycast, OverlapCircle, etc rather than a child collider and relying on physics messages
sage tulip
#

is the Enemy Rigidbody dynamic or kinematic?

#

Rigidbody2D*

hushed rose
#

rainVisualEffect.SetVector3("Camera", playerTransform.position); - Value of name 'Camera' was not found

slender nymph
#

that doesn't look like unity 🤔

hushed rose
#

Visual effect

void jacinth
slender nymph
hushed rose
#

k thx

sage tulip
slender nymph
#

their issue with their current setup is that they are using OnTriggerEnter2D instead of OnTriggerStay2D since they confirmed that it checks the collision once then not again

#

but they should still consider using a physics query instead of relying on physics messages

void jacinth
sage tulip
slender nymph
#

MoveTowards isn't even the rigidbody method, it's a Vector3 method. they are probably moving it via the transform if that is what they are using

sage tulip
#

Kinematic rigidbodies aren't affected by physics simulations. All movement has to be coded.

slender nymph
#

MovePosition is the Rigidbody method

sage tulip
#

ah wait

#

I misread

#

ignore my previous replies

#

MoveTowards is a Vector3 method

#

it should work

#

but still, made for Kinematic

void jacinth
#

The movement does work, yes.

#

I just had problems with the trigger only checking once, I know it is normal, but I am just trying to find a way to check repeatedly.

sage tulip
#

It will work, but if you introduce physics forces, there will be jittery movement.
If you aren't relying on realistic physics simulations from forces or collisions, then you can just make it kinematic.

void jacinth
void jacinth
slender nymph
#

yes, but you should still use a physics query instead

sage tulip
#

Yes, though I don't think it triggers on Enter or Exit.
Depending on the game, trigger colliders can be used, but it is more optimal to at least include a Raycast, which will probably be necessary when walls are involved

#

I'd use a Trigger for the Range
and while in range, raycast towards player, to confirm Line of Sight

void jacinth
#

I'll look into that, I have not used that before.

#

Thank you guys for the help!

rare basin
#

Hello I have a problem with DOTween. I have an UI element that I want to move to X local position set in the inspector.
transform.DOLocalMoveX(insideXValue, insideMoveDuration).SetUpdate(true);
I've set my insideXValue in the inspector to -300, but the object moves to -1260, why is that?) Screenshot is from runtime after the tween finish

sage tulip
#

@void jacinth PS: About the enemy movement
Either rework the code to use AddForce or velocity,
or simply make their Rigidbodies IsKinematic = true
so that the movement isn't messed up by physics forces like gravity

atomic bison
# burnt vapor Have a additive scene that is always active, containing components that should p...

Thanks so much for reply. I have a persistent scene as you say with my managers, and i load different scenes are additive yes, the info that i. want to save are position of items dropped or activated. So im testing right now if each gameobject (i only need it for around 20 items required for puzzle) got his scriptable info and when i load a new game i reset the info, i never has been used json, is better solution instead of using scriptable data for each item?

royal ledge
#
    {
        return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, .1f, jumpAbleGround);
    }```
This boxcasts returns true when my character touches the walls and roof aswell and not only the ground, anyone know why?
#

Seems simple enough to me, can't really wrap my head around why it should not work, i don't touch my collision box in any other way

queen adder
royal ledge
#

yes

queen adder
#

there you go

royal ledge
#

but the box cast should only cast downwards no?

#

vector2.down and 0.1f

slender nymph
#

your box is probably too large. it's the same size as your collider

queen adder
royal ledge
#

It is the same size as my collider, and the collider collides into things, so the box shouldn't be too big

#

Ye i think i'll just do that

slender nymph
#

if your collider can touch it, then so can the boxcast

#

use an OverlapBox that is small and just at the player's feet. no need to actually cast it

royal ledge
#

Aight i'll check it out, ty

queen adder
unreal meteor
#

what programming program would you guys recomend? until now ive just been using notepad

slender nymph
#

visual studio

#

also !ide 👇 make sure it is configured

eternal falconBOT
#
💡 IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

VS Code*
JetBrains Rider
Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

unreal meteor
slender nymph
#

an IDE is the integrated development environment. aka Visual Studio. having it configured means it will provide error and syntax highlighting as well as autocomplete

crude prawn
#

how do i check if my player has collided with any gameobject in a gameobject array?

slender nymph
#

do you know how to loop over an array?

unreal meteor
slender nymph
crude prawn
slender nymph
#

well then surely you know how to check if an object is in an array.
also what is the purpose of this because there's usually a better way than checking if the colliding object is in an array

crude prawn
#

im trying to get so if my player collide with an obstacle it dies

unreal meteor
#

wait nevermind i just accidentaly clicked on a pop up of microsoft ignite

crude prawn
#

yes but how do i check if my player has collided

#

is it oncollisionenter?

unreal meteor
#

wait why is visual studio 13 GB?

slender nymph
#

because that's how large it is

unreal meteor
#

damn

#

isnt there something smaller?

slender nymph
#

if you hate having working tools you can use vs code instead

#

or if you don't want to get help with your code in this server you can continue using notepad

crude prawn
#

im here rn how do i check if it has collided with any go in my array

slender nymph
#

don't bother with that. just check for a tag

#

unless you want to have to add every single obstacle in your game into an array

crude prawn
#

nvm

#

how do i check for a tag?

#

if my collision has collided with a gameobject in that tag xd

ivory bobcat
crude prawn
#

so if(collision.gameobject.tag == "Obstacles")?

slender nymph
#

use the CompareTag method rather than string equality to check tags

ivory bobcat
crude prawn
#

idk this doesnt work

slender nymph
#

the objects you are colliding with will need that tag, yes

crude prawn
#

thats basically then the same as putting them in an array

#

but anyways it still doesnt work

slender nymph
#

it is nothing like that

ivory bobcat
slender nymph
#

because with an array you'd need every single instance of each obstacle in your array

crude prawn
#

whats the issue with this?

slender nymph
#

what hav eyou done to make sure that OnCollisionEnter is actually being called? have you put any Debug.Logs anywhere or used any breakpoints?

crude prawn
#

yeah i got the debug.log

#

still nothing

slender nymph
#

where? because i don't see it in your screenshot

crude prawn
slender nymph
#

put it outside of the if statement

#

also wtf censoring your log? lmao that's a new one

crude prawn
#

hahaha

slender nymph
#

oh and if you could stop sending screenshots of !code that would be nice

eternal falconBOT
#
Posting code

📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

crude prawn
#

yup still no debug

slender nymph
crude prawn
#

i still have no idea whats wrong

slender nymph
#

have you gone through all of the steps in the link i sent?

royal ledge
#

@slender nymph @queen adder
If i have velocity towards the wall it still returns true in the air. If i make the overlap box smaller in width than this it works, but the setback being that if i am only standing on the corner of a tile i obviously can't jump. Will a raycast solve this issue?

crude prawn
#

oh wait

#

that script is in gamecontroller

#

bruh

slender nymph
royal ledge
#

The issue being that on that picture, it is to wide to work, as it returns true if i jump towards the wall (Playing my landing animation)

#

So i can't make it wider

#

So the bounding box is within the tiles for a frame maybe

#

lol i just realized you can even see the frame where it happens

slender nymph
#

yeah looks like your collider is penetrating into the wall. that usually indicates you are not moving in a very physics friendly way

subtle hedge
#

hey i have a problem wi visual studio, it's attached to untiy but there is no autocomplete

pseudo frigate
# ivory bobcat The direction would be equal to the point you're wanting to look at minus your c...
            Ray cameraRay = cam.ScreenPointToRay(Input.mousePosition);
            Plane ground = new Plane(Vector3.up, Vector3.zero);
            float rayLength;

            //Turret Rotation
            if (ground.Raycast(cameraRay, out rayLength))
            {
                Vector3 pointToLook = cameraRay.GetPoint(rayLength);
                pointToLook.y = partToRotate.position.y;
                Vector3 dir = (pointToLook - partToRotate.position);
                Quaternion turretRotation = Quaternion.LookRotation(dir.normalized, Vector3.forward);
                partToRotate.localRotation = Quaternion.RotateTowards(partToRotate.localRotation, turretRotation, turretRotationSpeed * Time.deltaTime);
            }

what did i do wrong here? the characters turret is looking into the ground instead of where the mouse cursor is

pseudo frigate
subtle hedge
#

i even tried to regenerate the files

royal ledge
#

@slender nymph I double checked my code for proper movement, seemed fine, switching the collision detection from discrete to continous solved it, thanks alot for helping out!

slender nymph
royal ledge
#

no, rb.velocity

tawdry rock
#

Hello. I need help how can i make a raycast ignore a layer? A quick google search told me i need to put a ~ before the layer name but its not working for me. I made a new layer, put it on the player and refferenced it in the gunshoot script. when i raycast if(Physics.Raycast(gunCamera.transform.position, fwd, out hit, gun_range, ~pLayer)) and debug the collison name it still hits the player... and yes i named my mask pLayer because i found that funny. AYAYA

languid spire
#

and then use ~ to invert it

tawdry rock
#

at the refference i used public LayerMask pLayer; this what you mean?

languid spire
#

depends what you put in there

tawdry rock
#

the layer that i made for the player called "Player"

languid spire
#

so what is the Id number for the Layer 'Player'?

tawdry rock
#

3

languid spire
#

ok, so if you debug.Log the variable player it should contain the value 8

tawdry rock
#

i don't really get it wym. why does ~pLayer simply not work?....

languid spire
#

A Layer Mask is a bitshifted value from a Layer id so...
if you have a Layer Id of 3 the mask is 1 << 3 which results in the binary 1000 which in decimal is 8

polar acorn
#

These are very different

wintry quarry
tawdry rock
#

Sry, was busy.. so

#

and obviously put the Layer 3 "Player" on the player gameobject itself

polar acorn
#

It'll pass straight through any collider with that layer

tawdry rock
wintry quarry
subtle hedge
#

autocemplete is not working but visual studio is attached to unity, i tried regenerating the files and reinstalling

eternal falconBOT
#
Visual Studio guide

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

Visual Studio (Installed via Unity Hub)
Visual Studio (Installed manually)

polar acorn
wintry quarry
# tawdry rock

is this the whole obbject? Are the colliders on a child object?

#

Where are the colliders

subtle hedge
wintry quarry
tawdry rock
subtle hedge