#💻┃code-beginner

1 messages · Page 442 of 1

fair steeple
#

It still isn't working

spiral glen
#

changing the material doesn't do anything, I just tried

rich adder
languid spire
#

you need to add it all the way down the inheritance chain

spiral glen
# rich adder it works just fine, you probably did it wrong...

that's normally the case

{
    [SerializeField] Renderer playerRenderer;
    
    [SerializeField] Texture2D[] backgroundTextures = new Texture2D[2];
    void Start()
    {
        int random = Random.Range(0, 2);
        Debug.Log(random);
        playerRenderer.material.mainTexture = backgroundTextures[random];
    }
}```
rich adder
rich adder
#

by swap material I mean make the material already with texture you want then just swap material on renderer

spiral glen
#

that's what the unity thing you sent told me to do

fair steeple
#

I just added it to all these and still nothing :/

rich adder
spiral glen
#

the issue is I have texture2D's and idk how to make a material

rich adder
#

thats how textures are displayed

#

unless you're doing UI ig

spiral glen
#

it's not ui

raw token
spiral glen
#

I put texture2D so that shouldn't be an issue

glad rune
#

why can i destroy the gameobject on the update function but not in destr function, the script is in a prefab (its the pipes in flappy bird)``` cs void Update()
{
transform.position = transform.position + (Vector3.left * PipeSpeed) * Time.deltaTime;

 if (transform.position.x < DeadZone)
 {
     Destroy(gameObject);
 }

}

public void Destr()
{
Destroy(gameObject);
}

summer stump
#

Did you add it to PlayerBaseState

glad rune
fair steeple
summer stump
#

That is cropped. PlayerBaseState does not inherit from anything, right?

#

Also, do you have ANY errors in the console? Not necessarily errors related to these classes, but ANY

fair steeple
#
using UnityEngine;

[System.Serializable]
public abstract class PlayerBaseState
{
    public abstract void EnterState(PlayerStateMachine playerStateMachine);
    public abstract void UpdateState(PlayerStateMachine playerStateMachine);
    public abstract void OnCollisionEnter(PlayerStateMachine playerStateMachine);
}

clean as a whistle

#

Maybe it's not working because I instantiate them directly from the script?

summer stump
#

Might be an issue of doing new() in the initializer? Not sure

fair steeple
#

I'll try another way

#

Nope

#

Even without using new

rich adder
fair steeple
#

I'll just assume it's a unity bug and work around it

glad rune
#

just dont understand why i could do it in the update func and not in destr func

languid spire
rich adder
#

yes sounds like you're trying to destroy the prefab not the instance

glad rune
#

how do i destroy the copy

rich adder
#

references

#

var myInstance = Instantiate(etc..
...
myInstance.Destr()

#

idk what you're trying to achieve so it depends, you might even store it as a field or in an list?

glad rune
#

just destroying all the copies on the screen

rich adder
#

all at once?

#

store all the spawned copies in a List then loop through to destroy them all when needed

charred spoke
#

That would destroy all spawned copies not the ones just on the screen however

rich adder
#

oh if they mean literally within screenbounds, i suppose to can check that too if its within bounds of screen

trail harbor
#

Anybody with some knowledge in the kinematic character controller done by philippe ?
I need to know the correct way of moving an AI character smoothly, it just teleports atm

glad rune
#

yeah im making a revive mechanic and all i have to do left is to destroy the obstacles on screen so that the player doesnt hit them while hes static for 3s

rich adder
#

positioning check probably being most performant but takes a bit of math

potent echo
#

I have an Enemy object that flips directions by multiplying his transform.localScale.x by -1.

The enemy has a child object (healthbar) that I don't want to be affected by the parent's change of localScale. How can I do this?

rich adder
long jacinth
#

so im making a game where chess pieces are enemies so i want the knight piece to dash at the player

#

so do i add force and make him go in the players direction?

rich adder
#

its an option sure

long jacinth
#

ok

raw token
# fair steeple I'll just assume it's a unity bug and work around it

I don't think unity will serialize an abstract class to a value... You can use a [SerializeReference] attribute on the field, but your abstract class itself does not have any serializable members, so I don't think there'd be anything for Unity to draw to the inspector except for an empty drawer

summer stump
#

So it is a non-abstract child class

raw token
#

Oh I see 👍

#

I guess then the question becomes "Does MovingState have any serializable members?"

pallid nymph
# raw token I don't think unity will serialize an abstract class to a value... You can use a...

I've made a package with a custom inspector that allows you to do [SerializeReference, TypePicker] private IInterface/AbstractClass field; and it'll show nicely in inspector and give you a picker to select concrete instance and fill its stuff: https://github.com/pulni4kiya/unity-editor-tools
I use this all the time in all my projects, because it's very convenient to be able to serialize interface/abstract class

#

(what's the policy on sharing one's packages when they're kinda relevant to the context? 😅 )

slender nymph
#

that's not really going to matter if there is nothing to serialize in the object

long jacinth
#

not really working still i find it under -1

#

wiat

#

im stupid

slender nymph
#

Mathf.Clamp returns the clamped value, it doesn't do it in place

long jacinth
#

i have to do currentGas = before it

#

damn

#

my game is coming together well

#

i want to thank you guys for helping if i didnt have ur help i would have been like my friend yassin we dont really talk about him

mint remnant
#

THis is a bit baffling to me
https://gyazo.com/eba7cc5f32189d57f0ce62c8a2982323

        Color [] colourMap = new Color [width * height];
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                colourMap [y * width + x] = Color.Lerp(Color.black, Color.white, noiseMap [x, y]/10f);
            }
        }
        colourMap [0] = Color.red;
        colourMap [12] = Color.yellow;
        texture.SetPixels(colourMap);
        texture.Apply();

The red pixel, upper right corner of the plane (index in the setpixels of 0) is landing in the opposite corner I'd expect. Couldn't find anything in docs stating the setpixels array is like this.

#

Actually hte docs do state the exact opposite of what is occurring: colors must contain the pixels row by row, starting at the bottom left of the texture. The size of the array must be the width × height of the mipmap level.

spark glacier
#

Hey so can I ask questions in this channel?

mint remnant
#

Yes, but you're limited to 1 and you just used it up

spark glacier
#

okay lol

prime pebble
#

So, i stg I just took a class on Function but for the LIFE of me I can't get them right lol I mess them up EVERY time. This is Python script.

half egret
#

This isn't a channel for any code help, it's specific for unity. The function is just returning whatever you pass in though, and the "str + x" line is doing nothing.

#

And the print line is out of scope of the function as well

#

And you never call the function

#

The code doesn't really make any sense

prime pebble
#

Oh, sorry i saw "beginner code" and was like "that's where I gotta go." lol I see, so I need to play the Print function within in the Function right?

half egret
#

Depends on what your code is trying to accomplish, I'm not sure exactly what you want.
That being said you'll get better targeted help for Python in any Python related discord. I cannot send any invite links but it's very easily googleable.

#

To the best of my knowledge, python isn't really used in Unity aside from automation

prime pebble
#

Fair, alrighty thanks for the help!

ionic zephyr
#

Hi guys, Ive got aproblem in which I have 3 menus that show three different types of objects but the information display in each of them shares some data like the name or the description of the different objects, however, there are some things that they don´t share, for example, weapons have damage quantity but resources don´t, any ideas of what should I do code-wise?

#

my idea is to click a Slot and show the information on the different menus, the problem is that not all the menus show the same information

hushed hinge
#

#1265813900037853255 message is am currently with the issue of increase my counter and have it persist across scenes and runtime, since I don't know how to fix that so the number in the stage selection can be increased from touching the muon objects in the other stage scenes

long jacinth
#

i know this is a stupid question but its late and my brain is not functioning the problem here is that its looping

#

so its keeps going in the z rotation -10 then 10 then -10 then 10

ionic zephyr
#

Is it okay to check if an interaction (with unity events) has been executed in the update method?

cosmic dagger
raw token
ionic zephyr
ionic zephyr
long jacinth
#

i think i might be cooking nvm

cosmic dagger
#

If that bool variable is true, then the event was invoked . . .

raw token
# ionic zephyr Imagine an inventory with three tabs, weapons, resources and key objects. The we...

I myself would aim to keep the inventory UI generic, such that you're not building different UI specifically for different types of inventory items. It kind of sucks to add a new stat to some type, or an entirely new type, and have to tweak the UI each time.

If the items themselves are capable of providing a list of their relevant stats, then the UI's only job is to display that list, and it will inherently work for all items.

ionic zephyr
#

public void Interact(InputAction.CallbackContext context)
{

}

ionic zephyr
ionic zephyr
raw token
# ionic zephyr So is it better just to have one tab with all objects and have only ONE manager ...

That's a design decision - your call. But I think tabs and filters are always nice.

All I'm saying is that instead of creating code to implement different menu for each type of item, I would try to create a single implementation that doesn't care that there are different types of items or know about which specific stats it needs to display. It just displays whatever it's given.

and have only ONE manager
I would only have one controller or manager here, yeah - at least, if all of these items are in the same inventory. If multiple tabs aren't simultaneously being displayed on screen at once, then all a tab is doing is filtering the items which are to be displayed. One UI controller feels convenient and intuitive to me, but you could certainly implement it with multiple.

ionic zephyr
ionic zephyr
raw token
ionic zephyr
#

yes

ionic zephyr
cosmic dagger
ionic zephyr
cosmic dagger
sleek gazelle
#

Hi, just wanted to know, is there any better way to do something like this? Cause rn it setactive(false) all game objects and then it only setactive(true) the one I wanna keep but that means the one I want to keep are setactive(...) twice

    public void HideEverything(){
        gameMenu.SetActive(false);
        textLogo.SetActive(false);
        levelModeExtraButtons.SetActive(false);
        levelSelectionMenu.SetActive(false);
        coinsCount.SetActive(false);
        gameHUD.SetActive(false);
        lastChance.SetActive(false);
        deathScreen.SetActive(false);
        nextLevelButton.SetActive(false);
    }

    public void ShowGameHUD(bool debug = true){
        HideEverything();
        gameHUD.SetActive(true);
    }

    public void ShowLevelSelectionMenuHUD(){
        HideEverything();
        levelSelectionMenu.SetActive(true);
    }

    public void ShowMainMenuHUD(){
        HideEverything();
        gameMenu.SetActive(true);
        textLogo.SetActive(true);
    }

    public void ShowLevelModeDeathScreen(bool extra = false){
        HideEverything();
        deathScreen.SetActive(true);
        levelModeExtraButtons.SetActive(true);
        if(extra){
            nextLevelButton.SetActive(true);
        }
    }

    public void ShowInfiniteModeDeathScreen(bool extra = false){
        HideEverything();
        deathScreen.SetActive(true);
        if(extra){
            lastChance.SetActive(true);
        }
    }
raw token
# ionic zephyr Hmm I see, however, how is this translated to code?

Invader's describing something like:

public InputActionReference InteractInputAction;

void Start() {
  InteractInputAction.action.performed += HandleInteraction;
}

void HandleInteraction(InputAction.CallbackContext _) {
  if (!InRange)
    return;

  InteractAction.Invoke();
}

void OnDisable() {
  InteractInputAction.action.performed -= HandleInteraction;
}

I've not worked with PlayerInput, so your actual implementation might vary depending on your Input System workflow. But this maybe illustrates the general idea.

cedar mirage
#

is it better to use the unity built in animation tools? or to do it all with coding?

#

ive heard you can do either

#

but im not sure what is better practice

#

well im just referring to a 2d platformer

#

for the player movement

#

like walk,idle,jump

slender nymph
#

please finish a thought before pressing enter

cedar mirage
#

I said the thought was not finished?

#

I just broke up the statements

slender nymph
#

mate you sent 6 messages in the span of 2 minutes. that could have all been one or two messages at most. see #📖┃code-of-conduct

cedar mirage
#

I did, but you're assuming I didnt finish thinking before pressing enter

#

but I got you I dont mind doing paragraphs either

slender nymph
#

here you go doing it again

cedar mirage
#

where?

#

2 messages lol

cosmic dagger
summer stump
rocky canyon
#

u can also animate in 3d modelling programs like blender

#

and/or use tweening libraries + code if thats the kind of animation u mean

jaunty bay
#

hi guys, quick question

#

do u guys usually use one object for both Warper and SpawnLocation (for landmark) or one for each?

#

for example, when i exit the room through the red door, i want my player to go back through that red door (just like how real life works)

#

actually, better question:

#

can i have a door that has some kind of extension in which it sets a spawn point? like, some button to "addSpawnLocation" and then i can drag that spawn location to a spesific coordinate

north fulcrum
#

so like the screen fades in and out and you're somewhere else, in front of the red door?

jaunty bay
honest trench
#

wsg, how do i make 3d character controller movement more snappy. right now if i walk, and then let go of w, it takes a second before the player stops moving. whats the solution to this weird problem?

summer stump
summer stump
honest trench
#

welp that was simple, thanks lol

#

god but now my animations are not smoothly transitioning because they dont have time to transition

#

let me attach a video hold up

#

what else can i show to help solve this

jaunty bay
#

ok, so heres what i understand

#

DDOL is runtime storage of data, in which it stores data only across scenes, but not after you close the game

#

PlayerPrefs are stored between game restarts, so it's ideal to be used as save points

steep walrus
#

https://www.youtube.com/watch?v=swOfmyJvb98&ab_channel=Mike'sCode
Im following this tutorial and for whatever reason it looks like this groundcheck is not working. I put it exactly where he put it in the tutorial, at the bottom of my player. and followed the steps to make sure the correct empty was put as the variable and the correct plane was put as the ground mask. Yet when I start my game I fall for a second, underneath my plane and then the collision starts working like it should a few feet higher. I'm getting a warning in the console that says my variable "isMoving" is assigned but its value is never used even though my code is exactly like the tutorial. I don't think it is related to that though

#unity #fps #tutorial
In this series, we are going to create a first-person shooter game in unity.
We will learn how to develop all the different features that are common in FPS games.
From basic movement to shooting modes, impact effects, animating the weapon models, ammo management, enemy ai, and more.

Full FPS Playlist:
https://www.youtube...

▶ Play video
rocky canyon
#

theres an extra collider in that picture.

steep walrus
steep walrus
#

or is that the only collider and I need to align it to the player

#

I aligned it to the player all is working fine

summer stump
steep walrus
# rocky canyon theres an extra collider in that picture.

even though it is working fine its kind of annoying I am getting the warning about my bool variable "isMoving" being assigned but not used even though it is "used" in an if statement. If I am getting that warning does that mean I have bad code? can I fix it? is it like a falty warning or something?

rocky canyon
#

ur just setting isMoving ur not technically using it there..

steep walrus
#

thats the only time it is referenced besides the top of the file where I just wrote bool isMoving;

rocky canyon
#

the if conditional uses the lastPosition, transform, and isGrounded

steep walrus
rocky canyon
#

it just means isMoving isn't utilized yet... u havent used it.. u could delete isMoving = true; and isMoving = false; and the code wouldnt change any.

steep walrus
rocky canyon
#

i intend on using em eventually

quick kettle
#

Hello can anyone help me solve this error, ive watched countless tutorials and still cannot find a solution. Im a complete beginner with around 20 days of coding. This is the code that the error brings me to for line 20. I'm trying to make a script that holds the prefab of this obstacle that moves up and down but then i found out that the references of scripts on my prefab dont carry over, so then I tried to reference the game objects and im met with my error. One thing i think it could be is that on start up the things in the canvas of my game are disabled but i dont know what to do.

wintry quarry
#

the error is clear

#

it didn't find any object with that name

#

that's all

quick kettle
wintry quarry
#

make a script on an object that ISN'T disabled which referneces those texts, find that, and interact through that

#

this is all bad practice

#

reaching out to random objects and directly modifying them in once place like that

old dune
#

Hi can someone help me solve my problem? When I parent my player to a GameObject, the player doesn't follow the parent's movement

#

It only slightly moves in the direction the parent's moving

wintry quarry
old dune
#

Oh yeah I'm using a charactercontroller for my player

#

But shouldn't it only move when I use my mouse and keyboard?

summer stump
old dune
#

Oh I see, thank you

#

I have another problem though, when I repeatedly change the MeshRenderer material of my GameObject, for some reason my cpu usage for unity drops from 20% to 5%, and the charactercontroller follows the GameObject when it's parented to it

#

But that only happens when I repeatedly change the MeshRenderer for that one specific GameObject

#

I have other objects in my game where I repeatedly change the MeshRenderer but my game doesn't get laggy

quick kettle
teal viper
#

Wdym by laggy? How do you confirm it? Did you try profiling the game?

cold ruin
#

While learning Draggable Item on yt, I'm kind of struggle trying to move the "item" to another "slot" while it keep snapping right back to my original slot, does anyone know what am I missing here?

wintry sluice
#

Hi! I'm struggling with writing PlayMode tests.

#

I have a script that calls Screen.height.

#

It works in the editors Play Mode, but not in Play Mode tests.

#

There it gives a null.

#

I'm loading a scene in {Setup] with SceneManager.LoadScene("TestScene", LoadSceneMode.Single). Why is Screen null?

eternal needle
wintry sluice
#

The error is just

NullReferenceException: Object reference not set to an instance of an object.

The line in question is top = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height - 100, 0)).y. @eternal needle

eternal needle
#

theres only one thing i see here that could be, the Camera.main

wintry sluice
eternal needle
#

🤷‍♂️ not sure how thats related at all. Do some debugging and actually see whats null instead of assuming

wintry sluice
eternal needle
#

or you dont have the right tag on the camera

wintry sluice
eternal needle
wintry sluice
eternal needle
# wintry sluice Can you recommend resources for getting better at debugging? I'm still learning ...

its really just trial and error. the most basic way with Debug.Log and seeing what value is what. Solving null problems is ALWAYS the same. Find out what specifically is null, then you find out why. And most of the time you'll realize very quickly why something is null if you wrote the code
Theres also the debugger with VS (and i think rider) where you can pause execution and actually hover over the variables in your IDE to see what they are at that moment. theres a ton of features

#

you could look into tutorials for the debugger specifically, but the actual skill is just something you get with time

ashen trail
#

I couldn't solve this last time but how can I spawn a bullet on my player and not have my player die from the collision detection. like how do I say "Only kill the player if the bullet came from the enemy"

teal viper
ashen trail
#

how would I code that?

#

this is as far as I got last time but I just made myself confused

summer stump
ashen trail
#

The fire point is the player position but Im not sure if I did it right

summer stump
# ashen trail I couldn't solve this last time but how can I spawn a bullet on my player and no...

Since the thing you are detecting is a bullet, and not the enemy itself, you will need the bullet to have some script on it (or perhaps a tag) that you can check. If the check is false, do not call destroy 🤷‍♂️
Something as simple as other.CompareTag("EnemyBullet"); would work, or as 'complex' as if (other.GetComponent<Bullet>().fromEnemy) (fromEnemy being a bool you toggle when shooting the bullet)

summer stump
#

FirePoint is nothing, that is what I was getting at. It is not declared anywhere
Compare it to Player, which IS declared
Also note that = is an assignment. Lower in the script in that if statement, you want to COMPARE it, with ==
Lastly, instead of whatever that IgnoreCollision call is supposed to do, you can just return

ashen trail
#

Okay i will try to fix the code and be back in half an hour

cold ruin
summer stump
eternal falconBOT
cold ruin
# cold ruin While learning Draggable Item on yt, I'm kind of struggle trying to move the "it...

here is the code in my previous video, i hope this could be more clear
Draggable Item

public class DraggableItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    [Header("UI")]
    public Image image;

    [HideInInspector] public Transform parentAfterDrag;
    public void OnBeginDrag(PointerEventData eventData)
    {
        parentAfterDrag = transform.parent;
        transform.SetParent(transform.root);
        transform.SetAsLastSibling();
        Debug.Log("Begin Dragging");
        image.raycastTarget = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.mousePosition;
        Debug.Log("Dragging");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        transform.position = parentAfterDrag.position;
        transform.SetParent(parentAfterDrag);
        Debug.Log("End Dragging");
        image.raycastTarget = true;
    }
}

Inventory Slot

public class InventorySlot : MonoBehaviour, IDropHandler
{
    public void OnDrop(PointerEventData eventData)
    {
        GameObject dropped = eventData.pointerDrag;
        DraggableItem draggableItem = dropped.GetComponent<DraggableItem>();

        if (transform.childCount != 0)
        {
            GameObject current = transform.GetChild(0).gameObject;
            DraggableItem currentDraggable = current.GetComponent<DraggableItem>();

            currentDraggable.transform.SetParent(draggableItem.parentAfterDrag);
        }
        draggableItem.parentAfterDrag = transform;
    }
}
vernal bone
raw token
ancient rampart
#

I'm pretty new to unity (like, very new to it) and I need to have a file explorer pop up so you can select a .wav file, I got that part all set up with an audio source plugged in, but I can't seem to find the right way to make that file you choose get plugged in as an audio clip into the audio source, but I'm getting help from some other people and they're kinda just throwin code at me hahaha, I don't really understand what it's all doing, in the vid I saw to set up UnityStandaloneFileExplorer they let you open a .obj and it turned it into text in a textmeshpro game object, but doesn't really explain how to do something useful with it lol, and I'm struggling to figure it out for audio stuff


#if UNITY_WEBGL && !UNITY_EDITOR
    // WebGL
    [DllImport("__Internal")]
    private static extern void UploadFile(string gameObjectName, string methodName, string filter, bool multiple);

    public void OnClickOpen() {
        UploadFile(gameObject.name, "OnFileUpload", ".wav", false);
    }

    // Called from browser
    public void OnFileUpload(string filepath) {
        StartCoroutine(OutputRoutineOpen(filepath));
    }
#else

    // Standalone platforms & editor
    public void OnClickOpen()
    {
        string[] paths = StandaloneFileBrowser.OpenFilePanel("Open File", "", "wav", false);
        if (paths.Length > 0)
        {
            StartCoroutine(OutputRoutineOpen(new System.Uri(paths[0]).AbsoluteUri));
        }
    }
#endif

    private IEnumerator OutputRoutineOpen(string filepath)
    {
        UnityWebRequest www = UnityWebRequest.Get(filepath);
        yield return www.SendWebRequest();
        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log("WWW ERROR: " + www.error);
        }
        else
        {
            
        }
    }
}```
#

ik it's gotta go in the else section of the OutputRoutineOpen block

#

but idk what I need to do or where to look to figure it out

ancient rampart
#

so replace all the UnityWebRequest with UnityWebRequestAudio and then replace .Get with .GetAudioClip?

half egret
#

I would definitely not recommend telling beginners to use AI

wintry quarry
#

If people wanted AI help they'd ask AI, not here

ancient rampart
#

yeah I was gonna say, I typically tend to avoid that if I can

cold ruin
ancient rampart
#

so I can figure it out before actually tossing it to the misinformation bot

ancient rampart
#

ohhhh my bad, didn't know clicking it would give examples and stuff

#

thank you

sour fulcrum
#

my lack of math education is showing, apologies,
If I have a pool of rarities, how can i convert a 0-100% value into a rarity in the context of that pool (is this even possible)

eg.

  • Pool is 1,1
  • I have 50%
  • Result is 2
half egret
#

You mean mapping the percentage chance to a corresponding rarity?

topaz mortar
#

I would definitely not recommend telling

ashen trail
raw token
summer stump
#

Stop

half egret
#

I hate doing this but <@&502884371011731486>

north kiln
#

!mute 804862024525021215 1d don't post here if you don't want to contribute meaningfully. We have no off-topic.

eternal falconBOT
#

dynoSuccess shadowisbetter was muted.

queen adder
#

meh

old dune
#

but for some reason it isnt happening anymore

#

its fine now

eternal needle
summer stump
# queen adder meh

Not really a great response, especially as the first one to all the suggestions, with the more important suggestions seemingly ignore completely

Did you fix the Collision error?

queen adder
cedar bone
#

Do you guys reccomnd using svg instead of PNG? I've heard GPU's arent made to render SVGs

mint remnant
languid spire
languid spire
cedar bone
languid spire
raw token
#

@cold ruin After much digging and a small effort to replicate the problem - I cannot :/ . My drop events are triggered in a simplified hierarchy.

I think something in your scene has to be intercepting the raycast/event, but I'm not entirely sure how you might go about debugging that. Watching the Event System preview window thingy might be a good place to start

languid spire
mint remnant
languid spire
mint remnant
#

btw it's a square

languid spire
mint remnant
#

yea I've researched it a little bit, but coming up sorta empty, I beleive it's either a bug or at hte very least improperly documented. Possibly why I find so many people asking how to flip a texture responses

languid spire
mint remnant
#

is that using setpixels? if so can you try adding colorMap[0] = color.red to color just the 0th element as red?

#

mine is on a 3d plane, so not sure of the connection between hte 2

#

making the 0th element in the upper right, instead of the bottom left per the docs

crisp token
#

anyone know why this isnt changing animation controller's animation?

languid spire
cold ruin
half egret
#

Still experimental/preview

#

Limited support by the looks of it

#

I tried relatively recently to get an SVG in and it wasn't worth the effort/potential bugs, I just rasterized what I needed and used that instead.

#

Oh sorry it seems he already linked that

languid spire
thorn field
#

Having issues with Vector3.SignedAngle, doesn't seem to return the correct angle when you are facing the object with your back.
If i'm standing in front of the object with my back turned, the result is angle=120. Need help

Vector3 targetPosition = mainCamera.WorldToScreenPoint(TargetObject.transform.position);
float angle = Vector3.SignedAngle(Vector3.up, targetPosition, Vector3.forward);
eternal needle
thorn field
#

yes, I made a sanity check. Vector3.up, Vector3.forward, TargetObject are all the correct values

echo hamlet
#

After watching this tutorial up to 7:55
https://www.youtube.com/watch?v=Qxs3GrhcZI8
When ever i diel the angle it acts rely sensitive.
Video demo: https://drive.google.com/drive/folders/17OZNDa0erUUIYB1FWAjKwl7OjM21keHD?usp=drive_link

A tutorial showing how to implement the projectile movement formulas and functions in Unity Engine and why are they useful, what can you use it for.
The tutorial covers C# implementation.

Support me on Patreon: https://www.patreon.com/abitofgamedev
Follow me on Twitter: https://twitter.com/steffonne
Follow me on Instagram: https://www.instagram...

▶ Play video
eternal needle
echo hamlet
#

notice the difference between when he moves angle compared to me

drowsy totem
#

I have a question about inheritance and virtual variables (or a workaround) in Unity

Basically, can I change the type of an inherited variable in a subclass, in Unity?

public class Card : MonoBehaviour
{
    [SerializeField] protected CardScriptableObject cardScriptableObject;

and

public class PlayingCard : Card
{
    [SerializeField] PlayingCardScriptableObject playingCardScriptableObject;

So a base Card class, with variants (playing cards, tarot cards, pokemon cards, whatever). The base class just knows it needs an image.

The sub classes have more information, which depends on the type. Playing cards have suits and numbers, some cards could have names and costs and abilities, etc.

Is it possible to change the type of inherited variable in Unity? Generic C# answers started talking about fields vs properties, but I'm not sure that works in Unity's ScriptableObjects.

#

Should I just make the base class abstract?

eternal needle
teal viper
eternal needle
#

also new just hides it, doesnt override

drowsy totem
#

I think I need to watch a proper tutorial about this, hopefully that answers my questions.

arctic mantle
#

hi, someone know how to make a sprite move using the touchscreen like if i want to move to the left i have to drag the finger to left and press?

drowsy totem
#

I basically want to be able to use ScriptableObjects to define card data. 5 of Spades, 2 of Diamons, Joker, whatever. The SO would know the image it needs to use, and the suit and the value.

eternal needle
drowsy totem
#

However, I'm looking into this as a way to learn how to program card game mechanics, so I'm aiming to do a generic system that could be expanded to the needs of different card games.

I think making the Card class abstract helps quite a bit, but I'm facing other issues, so as I said I'm going to check out some tutorials and examples to see how other people have implemented this.

eternal needle
#

One thing that comes to mind is you could store it as CardScriptableObject and then in some method (maybe awake) you could try casting it to the PlayingCardScriptableObject. If the cast fails, throw an error because someone plugged in the wrong SO. Then you read all the information you need

drowsy totem
eternal needle
#

yea, you could even try casting in OnValidate which would prevent you from plugging in wrong values in the first place

winter tinsel
#

how make jump

#

the gravity is set to -200 because otherwise my body falls really slow

drowsy totem
#

playerbody.velocity tells Unity which direction the character is moving.

One way to do a jump is to add an up-force to the velocity, at each frame. However, then you'd have to manually change the amount of up-force each frame.

#

Currently, you replace the velocity with a new velocity each frame, so you have to add more stuff to it to make sure it "remembers" that it's supposed to keep moving up

#

If you just add direction += transform.up; , spacebar becomes a jetpack boost that constantly pushes the character up

winter tinsel
#

yeah

#

thats what i have rn

#

i thought 10 would be a small value but uh

drowsy totem
#

Which tutorials about basic movement have you watched so far?

winter tinsel
#

i went to jupiter

drowsy totem
#

It's 10 per frame

#

You may want to learn about Time.deltaTime

#

10 per frame is a lot.

10 * Time.deltaTimeis ten meters (ten Unity units) per second

winter tinsel
#

i made a simple topdown shooter game to learn the engine basics now im going to actually start developing the game i want to

#

and i figured out the movement on my own lol

drowsy totem
#

You don't know what you need to know, so I think it's good to watch a few more basic tutorials. Movement systems have lots of parts into them. I recommend making a few more practice projects first.

winter tinsel
#

i mean this is all practice, might even start a new project if this one gets too spaghetti code-like

drowsy totem
#

Smooth movement, jumping, dashes that don't go through walls, and then you get into stuff like coyote timers.

winter tinsel
#

im gonna build the game upto where my knowledge with my practice game ends

drowsy totem
#

deltaTime, too. Have you noticed that your character currently moves waster diagonally than straight? Holding down WD is faster than W or D

winter tinsel
#

mostly, the game is gonna be a walking sim lol

#

i mean not really just the run will be pretty detrimental

#

still usable just, better keep it for running away from mutants

drowsy totem
#

Still, I do recommend watching some tutorial about basic movement. You need to know when you're touching the ground, otherwise the jump will allow infinite air jumps.

Any way, one super simplified way to do a super simple jump is like this:

// GetKeyDown() is only true for one frame, not all the time
// the player can only jump again once they're not jumping
if (Input.GetKeyDown(KeyCode.Space) && isJumping == false )
{
    isJumping = true;
    jumpTimer = 0f;
}

if (isJumping = true) 
{
    // push upwards at specific speed
    direction += transform.up * jumpForce;
    // jumpTimer variable knows how many seconds have passed since the jump started
    jumpTimer += Time.deltaTime;
    // once the jump has pushed up for a specific time, it's over and the character falls down again
    if (jumpTimer > jumpBoostTime)
    {
        isJumping = false;
    }
}

#

However, there are several issues with this.

The character will basically have an invisible jetpack pushing them up at a constant speed, and when it stops, they are instantly falling down at maximum fall speed. So it's not a smooth jump arc, but a very uncomfortable, sudden motion.

The player can keep spamming space to jump constantly, even in the air. You'd need to add another condition to the initial if, && IsGrounded() , and make a function that returns a true or a false value, and checks whether the player was touching the ground when the jump button was pressed

cedar bone
#

Can seomeone explain this? From what I understand its grabbing the current rotation and lerping to the target rotation. But isnt the current rotation and target rotation the same?

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

public class WeaponSway : MonoBehaviour {

    [Header("Sway Settings")]
    [SerializeField] private float speed;
    [SerializeField] private float sensitivityMultiplier;
    
    private void Update()
    {
        // get mouse input
        float mouseX = Input.GetAxisRaw("Mouse X") * sensitivityMultiplier;
        float mouseY = Input.GetAxisRaw("Mouse Y") * sensitivityMultiplier;

        Quaternion rotationX = Quaternion.AngleAxis(-mouseY, Vector3.right);
        Quaternion rotationY = Quaternion.AngleAxis(mouseX, Vector3.up);

        Quaternion targetRotation = rotationX * rotationY;

        transform.localRotation = Quaternion.Slerp(transform.localRotation, targetRotation, speed * Time.deltaTime);
    }
}
winter tinsel
cedar bone
drowsy totem
winter tinsel
winter tinsel
languid spire
cedar bone
#

the code is working

#

i just dont understand it

drowsy totem
languid spire
cedar bone
#

: (

#

what part is wrong?

drowsy totem
#

While that's not the way Slerp is supposed to be used, I'm not sure if that's an objectively bad way of doing things

languid spire
winter tinsel
cedar bone
drowsy totem
#

LERP and SLERP are basically ways to transform value from A to B, by changing a third value.

LERP is supposed to, for example, transform from 0 to 1, or from 50 to 80, in a specific way.

SLERP is supposed to, for example, transform from forward to up, or from (0, 50, 180) to (-100, 50, 0), in a specific way.

languid spire
drowsy totem
#

That functions seems to use SLERP to change an initial value a little bit, but not all the way, so it's using SLERP in a way that it wasn't mean to be used. But if it works, and SLERP isn't super slow, it's not... horribad.

#

Just not elegant

cedar bone
drowsy totem
#

Yup, and they're meant to transform from start value A to end value B by using a third variable

#

but the example doesn't use the same A and B, so it's not actually doing that

#

If you like math, I have a video about that stuff

cedar bone
#

do u mean, it keeps adding a 3rd variable

drowsy totem
#

it's just a variable from 0 to 1

#

basically, how much to fix it

cedar bone
#

oh ok

drowsy totem
#

0% to 100%

#

The way it's meant to be used, A and B don't change, but the T (time / mix factor) does

cedar bone
#

hmm got it

drowsy totem
#

so that way works, but isn't the way it was meant to be used

cedar bone
#

does hte problem have smthing to do with the speed * Time.deltaTime

drowsy totem
#

Not really. That just means the change is happening constantly at a given small percentage.

The weird part is that A value is changing every frame.

cedar bone
#

ohhhh

drowsy totem
#

If you want to watch a video explaining this through math, you can check this https://www.youtube.com/watch?v=LSNQuFEDOyQ

a journey through decay and delta time (I had to learn differential equations for this oh boy)

Slides: https://www.patreon.com/posts/105228270 for my patreon supporters 💞
The slides are much nicer in person!! like, the AV team on site had me lower the refresh rate on my laptop because we couldn't get it to work otherwise, and on top of that, vi...

▶ Play video
#

But it's not needed to use lerp functions, it just goes into detail about the math side

cedar bone
drowsy totem
#

I don't know any

cedar bone
#

like for example if the users FPS is really low, then the t value would be higher than 1 i asssume

drowsy totem
#

then it just snaps to B position instantly

cedar bone
#

oh ok thats very good!

drowsy totem
#

any way, most likely it rotates something so it sways a little bit behind some other thing

cedar bone
#

cuase i used slerp previously

#

and i ahted having to add time.deltaTime

#

every time

drowsy totem
#

just a visual delay

cedar bone
#

it just feels dirty

drowsy totem
#

using LERP/SLERP this way is, arguably, something that feels dirty

#

but it works more or less

#

any way, as the video explains, lerp and slerp give different results on different framerates

#

so they should only be used for visual stuff that doesn't affect gameplay mechanics

cedar bone
#

anyway, I wanted some help understanding this

#

wait I think I get it

#

nvr mind I don't

#

cause isnt the pistol always at the desired position?

cedar bone
drowsy totem
#

for movement yes, but for lerp/slerp no

cedar bone
cedar bone
#

sorry if I'm being dumb

#

wait nvr mind I'm dumb

drowsy totem
#

8:00 or so, it says that yes, it works

vague wigeon
#

what causes this >_>

cedar bone
cedar bone
vague wigeon
long jacinth
#

oh

vague wigeon
#

what xD

vague wigeon
long jacinth
vague wigeon
long jacinth
#

egyptian?

vague wigeon
#

its complicated

#

UAE

long jacinth
#

damn hello brother

vague wigeon
#

hello

#

can u help me do u know in unity ?

long jacinth
languid spire
#

Guys, if you want to chat, do it in DM's, this is not a social server

long jacinth
#

ok

verbal dome
long jacinth
cedar bone
#

can someone at least explain to me how this line works?

languid spire
cedar bone
long jacinth
#

and i remove the RigidBody2D

languid spire
cedar bone
#

also I don't get why transform.localRotation isnt the same as targetRotation

long jacinth
cedar bone
#

thats the only other part I don't understand

long jacinth
#

so maybe keep moving until he collides with the player?

verbal dome
#

You wont get collisions without a rigidbody but if you use the ray to check collision anyway then maybe it is fine

long jacinth
languid spire
hot palm
#

I use input actions way too complex, is there a one liner for reading the value of a button? I cant find anything online or in docs 😭
like what value do I want to read??

buttonValue = InputAction.Map.Action.ReadValue</*???*/>();
verbal dome
long jacinth
#

so the player will still get knockbacked

cedar bone
#

targetRotation is not trying to get the rotation to (0, 0, 0) [Which is my desired rotation]

#

its making it lag a bit behind which is a bit proportional to the mouse movement

languid spire
hot palm
cedar bone
languid spire
hot palm
#

Button?

#

Wait is value -> key what I am looking for?

#

hm nah button should be button

long jacinth
#

@verbal dome i have a problem the enemy keeps going in the player

rocky canyon
#

they both have colliders?

long jacinth
#

and bec he keeps going in the player

#

he is pushed and appears on the oppisite side

rocky canyon
#

sounds like ur using the wrong type of movement on something

#

for example translation.. (setting the transform.position directly) will cause something like that.. it doesn't respect physics

rocky canyon
#

you either have to write code/logic for ur own collisions, or use rigidbodies for movement

long jacinth
#

and writing my own logic will probably take forever

#

only got 6 hours left in the jam

rocky canyon
#

use physics layers..

#

enemy doesnt interact with enemy
but enemy interacts with player

long jacinth
rocky canyon
#

yes, if u use a rigidbodys

#

this would make enemies ignore other enemies.. but still collide w/ player
once u assigned the layer to the GameObjects

long jacinth
#

the problem i have is the playr

#

he has a rigid body

#

wait

rocky canyon
#

and the enemies dont?

#

both will need rigidbodies to collide w/ each other

long jacinth
#

other types dont this one yes

#

i can make enemy not collide with other enemies later

#

but my player is a rigidbody

rocky canyon
long jacinth
#

wait i can maybe use a character controler 2d?

#

this will stop the player from pushing the enemy and the enemy from pushing the player?

rocky canyon
#

theres no such thing as a character controller 2d component.. ud need to build it or copy one online

rocky canyon
rocky canyon
#

unless u code it in urself

long jacinth
#

i think i can still switch i got time

rocky canyon
#

yea, theres plenty of basic ones online

long jacinth
rocky canyon
#

are you using 2D ?

#

Unity 2D Character Controller

#

but its not a built-in component so i can't say how they would act.. it'd just depend on the person coding it

#

a 3D Character Controller acts as i said.. but 2D doesn't have one out of the box

long jacinth
#

so if my player doesnt have rigid body it wont be able to push right?

rocky canyon
#

correct

#

unless u make ur own code to detect when ur touching something.. and push it like that

#

a rigidbody = physics

#

follow his video to figure out how to set it up

long jacinth
#

ok scrap this

rocky canyon
#

ya, b/c rigidbody is the most common way to move things around.. (takes less work)

rocky canyon
long jacinth
#

there is no way to disable rb right?

rocky canyon
#

what u mean by disable it?

long jacinth
#

disable the componenet through script

rocky canyon
#

you could freeze its position unless ur giving it input

#
void FixedUpdate()
{
    Vector2 direction = (player.position - transform.position).normalized;
    float distanceToPlayer = Vector2.Distance(player.position, transform.position);

    // If the enemy is too close to the player, stop moving
    if (distanceToPlayer > 1f)
    {
        rb.velocity = direction * speed;
    }
    else
    {
        rb.velocity = Vector2.zero;
    }
}``` you could just do something like this
long jacinth
#

also i cant build my scene bec of this silly thing

rocky canyon
#

u shouldnt call the class SceneManager

long jacinth
rocky canyon
#

it confuses it

long jacinth
#

ok

fickle plume
#

This should be in a thread really

long jacinth
#

Prevent RigidBody 2D from pushing Eachother

#

still problems

#

i found something

#

i can try making it static then dynamic

#

i kind of did it

winter tinsel
#

uh, why does the force sometimes not want to get added?

#

i have an if statement taht runs, but for some reason just when adding the force to an object it doesnt run

#

but the rest of it does??

#

and its inconsistent, sometimes it works sometimes it doesnt

ivory bobcat
#

Break the problem down. Does the if statement work as expected (it must work 100% of the time it's expected to work)

winter tinsel
#

it works but it doesnt

#

theres multiple things in the if statement

#

and one allways works but specifically the one that adds force doesnt

ivory bobcat
#

So it doesn't work - the if statement.

winter tinsel
#

but even then its inconsistent

ivory bobcat
#

It needs to always work when expected

winter tinsel
#

okay then no

ivory bobcat
#

So the addition of force shouldn't be the focus but rather the reasons why the if statement might not be working. You should provide some !code

eternal falconBOT
winter tinsel
#

wait let m try something

slate badge
#

Is there anyway to use box colliders without the physical touch? Like if the player goes through or in the object, an event will then occur.

ivory bobcat
winter tinsel
#

currently, the box is colliding with something tagged "ground" and grounded which is a bool is false

#

it doesnt change it to true

#

does the collider only work on the first collision?

#

does it not check continuously wether its colliding or not?

ivory bobcat
#

Maybe you're changing it back to false immediately

#

The above code doesn't show us when the if statement would be executed

slate badge
winter tinsel
slate badge
ivory bobcat
slate badge
#

Alr ty

winter tinsel
#

this is the only code that resets it

#

right now rage is = 0

#

which should be smaller than that value right?

#

meaning its not being set to false again

rocky canyon
winter tinsel
#

so its not setting it to false??

#

and all the conditions in the if are correct so why isnt it setting it to true?

rocky canyon
#

if its not true, the conditions are indeed not met

#

possible case of assumption

winter tinsel
#

well its not grounded,

#

the only condition that MIGHT not be met

ivory bobcat
#

You need to properly provide !code
Those small snippets do not show us enough of what's going on.

eternal falconBOT
winter tinsel
#

those small snippets are everything thats going on lol

ivory bobcat
winter tinsel
#

but grounded is NOT true

#

its currently false

#

which is one of the conditions

#

the other condition

#

is wether or not the bodies are colliding

ivory bobcat
#

Your concern was that it doesn't change to true. If the statement was reached, it will be true.

#

Your problem most definitely lies whatever

winter tinsel
#

and they currently are, my only assumption is if the collision only checks if its collided not if its currently colliding

#

single collision instead of constant collision something

ivory bobcat
ivory bobcat
winter tinsel
ivory bobcat
#

On Collision Enter would only be called when a collision occurred - the first time.

winter tinsel
#

thats what im saying

#

how do i constantly check if its colliding?

#

just oncollison?

ivory bobcat
#

Try the other message ||Stay||

winter tinsel
#

okay now it allways works

#

finally thanks

stable narwhal
#
    void Update(){
        if (CanMove){
            HandleMovementInput();
            HandleMouseLook();
            ApplyFinalMovements();
            // Enable Jump
            if (ShouldJump)
                HandleJump();
            // Enable Crouch
            if (canCrouch)
                HandleCrouch();
        }

        // Enable stamina system
        if (IsRunning){
            EnableStamina();
        }
        
        // Disable stamina system
        else if (stamina < maxStamina){
            DisableStamina();
        }
    }

Is it ok to have this in Void Update?
Cus im not sure what the (rules) are in unity on what not to use in void update

slate badge
#

When my character dies, the scene is supposed to reset but when my character does die. The scene resets BUT in the hierachy it states "SampleScene (is lost)"

lethal bolt
hot palm
#
SceneManager.LoadSceneAsync(index, LoadSceneMode.Single);
SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
jaunty coyote
#

Question, I have objects in my "Assets/Resource" path and im trying to load them, works flawleslly in editor but not in an exported build(Windows). Any ideas how could i fix it?

#
string objectPath = (objectsPath).Replace("Assets/Resources/", "") + "/" + d.Name + "/" + f.Name.Replace(".prefab", "");
GameObject tempItem = (GameObject)Resources.Load(objectPath);
pallid nymph
#

not sure you need the starting "/" in the path

zenith cypress
wintry quarry
jaunty coyote
#
private void OnEnable()
{
    foreach (Transform child in transform)
    {
        Destroy(child.gameObject);
    }

    DirectoryInfo info = new DirectoryInfo(objectsPath);
    DirectoryInfo[] dirs = info.GetDirectories();

    foreach (DirectoryInfo d in dirs)
    {
        DirectoryInfo subInfo = new DirectoryInfo(d.ToString());
        FileInfo[] files = subInfo.GetFiles("*.prefab");

        if (noneOption)//--------------
        {
            GameObject emptyElement = Instantiate(itemUiElemnt, transform);
            Sprite itemIconEmpty = null;
            emptyElement.GetComponent<ChangeText>().ChangeTextFunc("None", "0", itemIconEmpty);
            emptyElement.GetComponent<RetriveIten>().pathToObject = removeItem;
            emptyElement.GetComponent<ChangeText>().imageIcon = null;
        }
        //------------

        foreach (FileInfo f in files)
        {
            GameObject element = Instantiate(itemUiElemnt, transform);
            string objectPath = (objectsPath).Replace("Assets/Resources/", "") + "/" + d.Name + "/" + f.Name.Replace(".prefab", "");
            GameObject tempItem = (GameObject)Resources.Load(objectPath);

            int itemAmaunt = LoadItemAmaunt(tempItem);
            Sprite itemIcon = LoadCorrectIcon(tempItem);

            element.GetComponent<ChangeText>().ChangeTextFunc(GetItemName(tempItem), itemAmaunt.ToString(), itemIcon);
            element.GetComponent<RetriveIten>().pathToObject = objectPath;
            element.GetComponent<ChangeText>().imageIcon = null; //idk how
        }
    }
}
```this is the whole code
wintry quarry
jaunty coyote
#

its probably really clunky written but what it does, it bassicly make a virtual arsenal, similar to arma 3

jaunty coyote
wintry quarry
#

get rid of all the filesystem code

jaunty coyote
#

but i need the folders

#

like the folder names

wintry quarry
#

They will not exist once you build the game

#

Resources doesn't work that way

#

your approach here is fundamentally broken.

#

It will not work, you should rethink it

jaunty coyote
#

ig ill leave this project behind than, coded way to much to pull myself out

#

sounds stupid ye, but the whole thing built relaying on those folder names + it was more or less a testing one

languid spire
rocky canyon
#

oofsicle 🍭

jaunty coyote
rocky canyon
#

it happens..

jaunty coyote
#

was thinking of quiting this project bc of bad FPS framework i built so this is just a nail in the coffin

languid spire
rocky canyon
#

tis called refactoring ^

jaunty coyote
#

thanks for the feedback, will keep in mind for the future projects

zenith cypress
#

I mean, it takes little effort to move from folder names to just a scriptable object that can scan/populate an array that stores a folder name + prefabs in itself when you build the game/press a button in a custom editor.

#

Then you'd just read from that SO instead

#

Then you wouldn't even need resources at all

jaunty coyote
#

i see

#

either way, thank you all for the valuable info

grave furnace
#

hi guys, i got an object called player and theres a script on it that instances a prefab called hand. I need to reference the player inside a hand's script, can i pass the player object as a variable to the hand somehow?

#

thats confusing

grave furnace
#

that script communcation

modest dust
#

Make a method in the hand script with a player script param

#

And pass this after instantiating the hand

languid spire
grave furnace
#

guess im not doing it right

languid spire
grave furnace
wintry quarry
modest dust
#
public class Hand : MonoBehaviour
{
  private Player m_player
  
  public void Init(Player player)
  {
    m_player = player
  }
}

public class Player : MonoBehaviour
{
  [SerializeField] private Hand m_handPrefab;

  private void InitHand()
  {
    Hand handInstance = Instantiate(m_handPrefab);
    handInstance.Init(this);
  }
}```
#

For clarity I suppose

grave furnace
#

the class i created to code this

modest dust
#

The Hand class instance, yes

#

And a Hand prefab

#

If there's a Hand component directly on your prefab, you can drag and drop it into a Hand field in the inspector

north fulcrum
#

can i somehow make scripts broadcast messages that other scripts listen to so i dont have to acces both components every time? or is the latter just easier

wintry quarry
wintry quarry
#

You can use UnityEvent or C# events if you want events

modest dust
north fulcrum
#

so like lets say my character jumps and i want to forward that to the gui

wintry quarry
north fulcrum
#

do i have to acces both the character script and the text component to change that or is there an easier way

#

and im doing this in the character script

wintry quarry
#

note that events don't really save you from references, they just invert the dependency. I.e. instead of the Player script referencing the UI, the UI will reference the player in order to listen to the event.

wintry quarry
north fulcrum
#

in my code i have to reference them both as an object i think and im just wondering is that really the best way to go about it

grave furnace
#

whats the site we use to post a long code here?

wintry quarry
#

you will need references somewhere

north fulcrum
#

in the character script

eternal falconBOT
north fulcrum
#

in the update() function

wintry quarry
wintry quarry
# north fulcrum in the update() function

Options are:

  • Use a UnityEvent on the player and assign it to a function on the UI in the inspector
  • Use a C# event on the player and have the Ui reference the player to listen to it
  • Use a static C# event on the player class and have the UI script just subscribe to the static event
grave furnace
slate badge
grave furnace
#

am i doing it right?

wintry quarry
#

and GameObject player

grave furnace
summer stump
hot palm
grave furnace
#

i hate language barrier lol

#

almost using google translator

wintry quarry
slate badge
north fulcrum
wintry quarry
north fulcrum
#

why so?

languid spire
grave furnace
#

ok it says i can't convert handMoviment into GameObject

#

prob because im trying to instantiate the script not the prefab lol

north fulcrum
languid spire
polar acorn
summer stump
grave furnace
#

OH now i see that

#

i feel i was refusing to think

#

i replaced GameObject for var idk why

#

but it wont change anything i guess

#

what i don't understand is how am i instantiating a script?

languid spire
north fulcrum
#

is there a site with all the naming conventions specifically the ones like ``m_, g_ or __name`

summer stump
languid spire
north fulcrum
summer stump
polar acorn
grave furnace
grave furnace
#

to tell you guys what im doing

summer stump
grave furnace
willow scroll
summer stump
summer stump
#

What is the current issue then?

grave furnace
#

oh ok

#

now it says the object i want to instantiate is null

#

i have to drag it

polar acorn
grave furnace
#

when i drag the player, it says the type mismatches, since the type of the player referenced on the hand script is playerMovement (the script) should i drag the instead script?

#

no it doesn't work

hot palm
polar acorn
latent gale
#

help why is it giving me errors 😭 i have no idea whats happening

grave furnace
#

its an object on the scene

polar acorn
grave furnace
#

yes

languid spire
grave furnace
#

i can turn it in a prefab

polar acorn
# grave furnace yes

Prefabs cannot reference objects in the scene. You will need to set that value on the instance that is created in the scene

latent gale
#

i understand now but all these random errors just dont make sense

languid spire
polar acorn
#

You essentially cut your function in half by putting that there

#

and the first half has no ending braces, while the second half has no start

#

Hence all the other errors

latent gale
#

oh

grave furnace
#

thxx guys

latent gale
#

ph eeah i can see that now

#

thanks

grave furnace
#

everything is working now

so, when i instantiate the script instead of the prefab itself im instatiating the prefab if thats inside the root of it?

#

thats what i understand

grave furnace
#

is it possible to a script to be inside more than one object?

#

i mean

#

more than one prefab

languid spire
#

sure

grave furnace
#

then if i try to instantiate a script inside two prefabs what will happen?

languid spire
#

the inspector will accept any prefab that has that script on it

grave furnace
#

what

languid spire
#

you can only assign one prefab in the inspector, wdym by 2 prefabs?

grave furnace
#

oh i drag one prefab to the inspector so it won't have to choose one since i've already done

#

nvm

#

ok i get it

#

thx

slate badge
loud sage
#

is the rigidbody component toggleable through a script?
I'm trying to make a ball turn on its physics when I enter a trigger box but the toggle I'm supposed to work with per the tutorial I'm following isn't there for rigidbody specifically

rich adder
#

there is no enable/disable directly per se

#

if you are in 2D afaik there is actually one to disable it , turn off Simulated

loud sage
#

I'm doing the bonus scene in the fundamentals tutorial, adding a trigger for it in the kid's room

#

so it's a 3D scene

loud sage
loud sage
#

3D

rich adder
#

kinematic stops all velocity / outside forces from affecting it

loud sage
#

and that's workable then
my other Idea was gonna be an invisible bowl to cradle the ball that I would disable on trigger lol

loud sage
rich adder
#

or affected by outside forces (gravity)

hot palm
summer stump
loud sage
#

it's like ontriggerenter into rigidbody.kinematic toggle or something along those lines I figure

#

I'll figure it out now that I know what property to manipulate

hushed hinge
slate badge
dire torrent
hot palm
sage abyss
#

Hey, how do I get info from project settings? Like gravity in project

fringe plover
#

Is it ok to name value same as enum name? it wont cause any problems right?

slate badge
hot palm
full kernel
fringe plover
#

okay thanks

slate badge
hot palm
#

So currentRarity for example

#

If it's public it'd be CurrentRarity

fringe plover
#

ill mostly likely use WeaponRarity

hot palm
#

Yeah depends on what you need it for

sage abyss
summer stump
fringe plover
#

and its not state

summer stump
#

I know it is not a state. That was clear from the name. That was just an aside in addition to the previous statement

loud sage
#

I think I'm missing something
the console tells me it couldn't find the namespace for rigidbody

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

public class BallPhysicsTrigger : MonoBehaviour
{
//new classes to store properties of RigidBody component
public RigidBody rb;
public bool isKinematic = true;

// Start is called before the first frame update
void Start()
{
    rb = GetComponent<Rigidbody>();
}

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

private void OnTriggerEnter(Collider other)
{
    // Check if the object entering the trigger is the player (or another specified object)
    if (other.CompareTag("Player")) // Make sure the player GameObject has the tag "Player"
    {
        if (rb != false)
        {
            //turn off the Kinematic property and enable physics
            rb.isKinematic = false;
        }
    }
}

}

wintry quarry
eternal falconBOT
loud sage
#

oh ffs yeah

#

now it's whining about the output directory for the build, I don't know what that's about

rich adder
loud sage
#

the trigger works now tho

rich adder
loud sage
#

I've always had beef with custom classes, we go way back

rich adder
raw token
rich adder
loud sage
rich adder
#

yeah not configured

loud sage
#

retyped it wrong on purpose

rich adder
#

double check these steps !vs

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)

rich adder
#

also closing VS n clicking the Regen project files button after

loud sage
#

alright yea I was just using the virgin configuration of VS I as using for normal programming

rich adder
#

yeah its gonna make your coding better when you can pullup all the proper classes and whanot

loud sage
#

what's weird is that it did give me the suggestions for the autocomplete, but not the red underlines

rich adder
#

at least you will know it compiles with no errors, even the code doesn't work as expected sometimes lol

rich adder
raw token
#

I did update VS recently and noticed it seems to have introduced an AI autocomplete of some variety

loud sage
#

let alone the 2022 version

rich adder
#

well right now its not lol so I'd take care of that first

loud sage
#

alright

#

gotta love the random grunt work you'd have never thought you needed to do in order to not go insane 100 hours down the line

#

huh
it's all already there

#

same goes for the Unity hub & editor side

#

I did run an update in VS tho, maybe it was just a version conflict

rich adder
#

there are more steps to it

summer stump
loud sage
summer stump
#

Ok, and did you regenerate the project files as navarone said?

loud sage
#

okay I didn't know what that meant so my eyes kinda skipped over that part

summer stump
#

No worries. It makes sense to do it at the very end anyways

#

It is just a button in external tools. Only the top one or two checkboxes need clicking. That's all I do at least, I am still unclear on which are necessary. Definitely not all of them though

summer stump
#

It is in unity

loud sage
frosty hound
#

Fix up your name/profile if you want to use this server.

loud sage
#

celebrations are in order indeed
it's like 30 degrees C right now
I'm gonna double dip the ice cream after dinner 🫠

summer stump
#

Come on.....

raw token
#

🤦

frosty hound
#

!ban 920336052231749652 Shitty human being

eternal falconBOT
#

dynoSuccess 7moodyxd was banned.

loud sage
#

rip that guy
he showed promise to make irreverent slav jank

#

good riddance

long jacinth
#
    {
        if (DisplayVar != null)
        {   
            string FormatTime(float time)
            {
                var minutes = (int)time / 60;
                var seconds = (int)time % 60;
                return $"{minutes:00}:{seconds:00}";
            }
            val += Time.deltaTime;
            System.TimeSpan timeSpan = System.TimeSpan.FromSeconds(val);
            DisplayVar.text = timeSpan.ToString(@"hh\:mm\:ss");
        }
        else
        {
            val = 0;
        }
    }```
#

its not updating

raw token
#

Weird place for a local function 🤔

earnest rivet
#

Youre declaring a method inside a method

#

lol

rich adder
#

why did you make the function local

long jacinth
#

wait

#

so where am i supposed to declare it

earnest rivet
#

outside of Update

rich adder
#

the same place you declared the other ones

raw token
#

You're also not actually calling said function

long jacinth
#

alrght how do i call it tho

rich adder
#

i literally showed you verbatim where to place it & how to call it lol

earnest rivet
#

kek

rich adder
raw token
rich adder
#

you're confusing declaring vs calling @long jacinth

long jacinth
earnest rivet
#

I would highly recommend a beginner C# course.

#

So you can get a grasp of functions/methods, variables and the like

summer stump
long jacinth
full kernel
#

Are you even "finishing" it if you need people to spoon feed the code to you?

earnest rivet
#

Right, were giving you the solution but you don't know how to implement it

full kernel
#

Sounds like you're asking us to finish this jam for you

earnest rivet
#

So you're having the crowd do it for you

long jacinth
earnest rivet
#

You won't properly learn anything if you're copying and pasting

rich adder
#

or at very least know what you are copying & what it does

long jacinth
long jacinth
rich adder
earnest rivet
#

What is this jam for? Your life?

long jacinth
earnest rivet
#

Are you working on this by yourself?

long jacinth
#

actually thats a good thing my friend is convinced i should stop learning unity bec ai can do everything for me

earnest rivet
#

Your friend is delusional.

long jacinth
#

WORKS THANKS GUYS!!!!

loud sage
summer stump
earnest rivet
#

In the western world we call them a "Hater"

long jacinth
#

well he isnt a hater he tried learning unity too he just thinks that ai will improve to the point where u just tell it to make a game and it makes the game

polar acorn
#

Or a grifter

#

or both

long jacinth
#

he left that ideology thankfully

earnest rivet
#

maybe in a thousand years

#

but we wont be around to know

#

in the meantime, your friend is still delusional

ripe shard
earnest rivet
#

unless someone here is immortal or a lich.

long jacinth
#

maybe he is

#

idk

#

im gonna stop here and make a leader board

earnest rivet
#

Yes, go get your discord role

long jacinth
#

i was gonna make a high score

#

but no good

analog wraith
#
    {
        bossTransform = animator.transform;
        playerTransform = GameObject.Find("Player").transform;
        monoBehaviour = animator.GetComponent<MonoBehaviour>();
        initialWidth = UnityEngine.Random.Range(1.5f, 3f);
        initialLength = UnityEngine.Random.Range(2f, 4f);
        monoBehaviour.StartCoroutine(Trigger(animator));
        animator.SetTrigger("Return");
    }
    IEnumerator Trigger(Animator animator)
    {
        for (int i = 0; i < UnityEngine.Random.Range(3, 5); i++)
        {
            yield return new WaitForSeconds((i) * Random.Range(.15f, .3f));
            // monoBehaviour.StartCoroutine(Fire(widthMultiplier, lengthMultiplier));
            Debug.Log("HI");
            widthMultiplier *= Random.Range(1.5f, 2f);
            lengthMultiplier *= Random.Range(1.5f, 2f);
        }
    }```
Could someone help me with this? I'm trying to make it so when I enter the state I start a coroutine that happens independently and I call SetTrigger("Return") to go back to the preivous state the next frame. Problem is it seems to be waiting for the coroutine to finish before returning to the previous state.
earnest rivet
#

The coroutine allows you to call the method without blocking the update calls

#

but still is technically "synchronous"

analog wraith
wintry quarry
#

btw:
i < UnityEngine.Random.Range(3, 5) you should really do this before the for loop otherwise it's generting a new int each iteration of the loop

#

e.g.

int count = UnityEngine.Random.Range(3, 5);
for (int i = 0; i < count; i++)```
analog wraith
#

ok wait thats really dumb mb ty for catching that

raw token
hushed hinge
# hushed hinge what doesn't is the number counter not going up when i touched a game object fro...
analog wraith
wintry quarry
analog wraith
wintry quarry
#

there's nothing in this code that waits for the coroutine to finish

#

unless widthMultiplier etc. are properties for example?

analog wraith
#

nah their just private variables

verbal dome
#

If yes, you should handle destroying duplicate singletons

hushed hinge
verbal dome
#

Well then my question stands but for MuonCounter instead of Counter

#

Are you sure that only one MuonCounter is instantiated during the game and when switching scenes?

hushed hinge
frosty hound
#

Thread

queen adder
#

How would I make a method run on a perfab when its instantiated

ripe shard
queen adder
#

So start is when it spawns in

wintry quarry
#

Awake and OnEnable will have run by the time Instantiate returns.
Start will run later, just before its first monobehaviour lifecycle function runs (FixedUpdate/Update, etc)

ripe shard
raw token
summer stump
ripe shard
summer stump
ripe shard
summer stump
#

Yeah, lotta control over the execution flow that way

ripe shard
#

you can basically inject your own lifecycle by hacking around these events

queen adder
#

How would I change the rotation of an object to face another in 2d?

wintry quarry
slender nymph
polar acorn
queen adder
wintry quarry
#

"YouTUbe tutorial makers hate this one simple trick!"

foggy osprey
#

I watched Codeer’s video on how to make a procedural animation. I need a bit of help with the second step of the video, which involves anchoring/fix the the bottom of the foot to the ground.Thanks!

eager spindle
#

not exactly sure what you mean. do you mean positioning the model so that the bottom of the model is in contact with the ground? or do you mean using IK constraints to detect the ground

long jacinth
#

oh my lord the game jam has over time

#

i just want to thank all of you guys

foggy osprey
eager spindle
eager spindle
#

im not sure what your setup looks right now but is your model positioned such that one leg is on the ground already?

hybrid gust
#

how would I go about finding out which child has been hit in code?
The parent gameObject that is highlighted has a rigidbody and the script I'm using. OnCollisionEnter (Collision) seems to only have members that can get me a reference to the sword that hit it, but not areference to the body part I've hit

ashen trail
#

how do I say "if the bullet spawns on the player don't do OnTriggerEnter " in code.

eager spindle
hybrid gust
eager spindle
eager spindle
foggy osprey
#

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

public class Walker : MonoBehaviour
{
public Transform Target;
public float maxDistance = 0.9f;
public float moveSpeed = 2f;
public float arcHeight = 2f;
private Vector3 startPosition;
private Vector3 endPosition;
private Vector3 arcMidpoint;
private float arcProgress = 0f;
private bool isArcing = false;

void FixedUpdate()
{
    if (isArcing)
    {
        PerformArcMovement();
    }
    else
    {
        CheckDistanceToTarget();
    }
}

void CheckDistanceToTarget()
{
    float distance = Vector3.Distance(transform.position, Target.position);

    if (distance > maxDistance)
    {
        // Börjar gå
        startPosition = transform.position;
        endPosition = Target.position;
        arcProgress = 0f;
        isArcing = true;

        // Calculerar var mitten är på Y axlen
        Vector3 midPointBetween = (startPosition + endPosition) / 2;
        arcMidpoint = new Vector3(midPointBetween.x, midPointBetween.y + arcHeight, midPointBetween.z);
    }
}

void PerformArcMovement()
{
    // Hur snabbt ska det gå
    arcProgress += Time.deltaTime * moveSpeed / Vector3.Distance(startPosition, endPosition);

    if (arcProgress >= 1f)
    {
        // gör klart animationen
        transform.position = endPosition;
        isArcing = false;
        return;
    }

    // Slerp från början till slut
    Vector3 positionToMid = Vector3.Slerp(startPosition, arcMidpoint, arcProgress);
    Vector3 positionToEnd = Vector3.Slerp(arcMidpoint, endPosition, arcProgress);
    transform.position = Vector3.Lerp(positionToMid, positionToEnd, arcProgress);
}

}

eternal falconBOT
foggy osprey
hybrid gust
eager spindle
#

unfortunately your hands are tied here

#

best to do the check in the sword now so when you have multiple targets later your sword code easily carries over

short hazel
#

Doesn't collsion contacts have a reference to both colliders?

#

Or that's only in 2D

hybrid gust
#

Unless I missed it

#

But so be it ig

short hazel
#

collision.GetContact(0).???, let me check

cosmic dagger
hybrid gust
ashen trail
hybrid gust
#

yup

#

it works

#

Granted I still thing Uldynia is right in terms of flexibility

short hazel
# hybrid gust checking rn

It does, there's otherCollider and thisCollider!
So as long as the Rigidbody is on the dummy object and the children have colliders, collision events will get reported bubbled up to the Rigidbody meaning you only need the script in one place, where the rigidbody is

eager spindle
# ashen trail sorry I just know a bit of coding from learning from unity courses. How would I ...

when you tag an object. you can easily check the tag of the object later on in case you wanna do stuff. Here, since we want to tag our player with the Player tag we don't have to do more checks.
https://www.youtube.com/watch?v=D2lLNZgCu6k

#JIMMYVEGAS In this Mini Unity Tutorial we explain why tags are vital in game development and how you can use them to manipulate your game.
✦ Subscribe: http://bit.ly/JimmyVegasUnityTutorials
✦ Patreon: http://patreon.com/jimmyvegas/
✦ FREE Assets: http://jvunity.com/
✦ Facebook: https://www.facebook.com/jimmyvegas3d/
✦ Twitter: https://twitter...

▶ Play video
#

very short video on this

#

I strongly recommend you to learn c# before you start coding in unity, have solid foundations

round mirage
#
Pepper = gameObject.transform.GetChild("Object Preview");

i want get child object of my gameObject with his name someone can help me 🙂

eager spindle
#

for some people they did dive straight into unity, that's also an approach. but for me I started learning a lot faster and understood a lot of things by learning programming(c++) before diving into unity