#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 301 of 1

kindred nest
#

this will not work, as you save the offset once, so if the player moves the camera stays in that one spot

#

you'd need to update it in the update, probably inside that if to avoid dumb calculations

rich adder
#

that would only work with a singlepoint though, if you want the whole circle you might need to do rect type overlap using math with rect sizes.
I think you can also check if bounds intersect ?

kindred nest
#

so getting closer, but not quite yet!

stuck palm
#

its easier that way so i can avoid doing annoying code if its overlapping two things

#

how can i do a raycast?

#

i know normal raycasts but is it different for UI?

rich adder
long jacinth
#

guys plsssssss help

#

this whole day i have been through this problem and i still dont know what the cause is

#

its so confusing and absurd

scarlet skiff
#

anyone?

dusk mural
#

wrong screenshot

kindred nest
#

yeah lmao

dusk mural
stuck palm
rich adder
# stuck palm circle is being moved like this ```cs if (_playerInputController != null) ...

maybe you can try

 [SerializeField] GraphicRaycaster gRaycaster;
    [SerializeField] EventSystem es;
    PointerEventData pointerData;

    void Update()
    {
        pointerData = new PointerEventData(es);
        pointerData.position = theCursor.position;

        List<RaycastResult> results = new ();

        gRaycaster.Raycast(pointerData, results);

        if (results.Count > 0) Debug.Log("Hit " + results[0].gameObject.name);

    }```
long jacinth
#

how can i debug stuff like this

kindred nest
# dusk mural

this will funnily enough distance the camera by -1 on each Update (so many many times a second), you might have confused transfom.position with player.position. Or just drop it and use -1f if you know the camera is not going anywhere in the z direction

long jacinth
#

can i open a furom for this problem because it seems to be a very long and complex one

kindred nest
#

also, using a constant in the third parameter won't do you any good, read the doc page i sent before and it will explain it nicely

scarlet skiff
#

pls bro how do i start playing an animation at its end?

polar acorn
stuck palm
rich adder
long jacinth
# polar acorn like what

my game when i jump it swaps the tile and disables the box collider, in the build it doesnt swap the tile but disables the box collider how can i debug what is happening with the tiles

kindred nest
polar acorn
stuck palm
kindred nest
# dusk mural This?

the most common approach is having some speed variable and multiplying Time.Timedelta by it as the third param

long jacinth
#

if(RedOn)
{
Tilemap RedTile = RedGrid.GetComponent<Tilemap>();
Tilemap BlueTile = BlueGrid.GetComponent<Tilemap>();
RedGrid.GetComponent<TilemapCollider2D>().enabled = true;
BlueGrid.GetComponent<TilemapCollider2D>().enabled = false;
RedTile.SwapTile(TileGrid,Tile);
BlueTile.SwapTile(Tile,TileGrid);
Debug.Log("RedOn");
}
else
{
Tilemap RedTile = RedGrid.GetComponent<Tilemap>();
Tilemap BlueTile = BlueGrid.GetComponent<Tilemap>();
RedGrid.GetComponent<TilemapCollider2D>().enabled = false;
BlueGrid.GetComponent<TilemapCollider2D>().enabled = true;
RedTile.SwapTile(Tile,TileGrid);
BlueTile.SwapTile(TileGrid,Tile);
Debug.Log("RedOff");
}

kindred nest
#

having a constant like 0.001f results in the camera staying in that in-between point of 2 positions specified

kindred nest
#

and you want it to eventually reach the target (player)

#

yup, docs are really great give them a shot!

rich adder
polar acorn
long jacinth
#

if (Input.GetButtonUp("Jump"))
{
if(RedOn)
{
RedOn = false;
}
else
{
RedOn = true;
}
}

polar acorn
scarlet skiff
#

i pass in normalized time (being 1), the animation has loop set off, yet it still plays the beginning, what did i do wrong?

kindred nest
#

no clue what the issue is, just letting you know šŸ˜†

long jacinth
long jacinth
#

its a problem in the tile swapping

#

but i think you have a point in the getcomponenet

#

so i will quickly fix that

kindred nest
agile kernel
#

really getting annoyed at this error while trying to build an android app ```Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8

FAILURE: Build failed with an exception.

  • What went wrong:
    Could not determine the dependencies of task ':unityLibrary:mobilenotifications.androidlib:compileReleaseJavaWithJavac'.

Failed to install the following Android SDK packages as some licences have not been accepted.
platforms;android-33 Android SDK Platform 33
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html

Using Android SDK: C:\Program Files\Unity\Hub\Editor\2022.3.24f1\Editor\Data\PlaybackEngines\AndroidPlayer\SDK

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 7s```

long jacinth
#

red wiggly line things appeared

kindred nest
summer stump
thorn holly
#

Local vs global scope

kindred nest
#

make sure to have them defined in the class-scope (outside any function) and assign their reference in the start() function.

long jacinth
#

i put it in the update

#

which doesnt seem smart

thorn holly
#

Could you theoretically store all static variables in one class and there wouldn’t be an issue with that?

summer stump
thorn holly
kindred nest
long jacinth
kindred nest
#

but, this is, to say the least, very naughty

thorn holly
#

Yeah, it seems like it would be very disorganized

kindred nest
#

yeah, nice for quick prototyping, but will bite you in the ass when you need to split it according to actual needs and responsibities notlikethis

thorn holly
#

Yeah, the only DontDestroyOnLoad singleton I have handles player connections, I’m planning on making another that’ll handle the pause menu

#

Speaking of which, for a pause menu, should I make it a separate scene that I load additively on a prefab that I instantiate?

kindred nest
#

Golden rule i follow is to not solve issues that don't exist yet, so avoid making the absolute dirtiest solutions, but also don't create a rainbow highway for 1 horse

thorn holly
long jacinth
#

ya the problem still happens

#

the problem is 100% in swapping tiles

kindred nest
thorn holly
#

Exactly lol

kindred nest
#

but hey, this might be a cool tool to sell on the marketplace for a quick buck someday

long jacinth
#

why cant the build be a good boy and copy the editor

queen adder
#

how do i get this ui text to be on the game screen?

summer stump
queen adder
#

oh so it has to be in that canvas to show up

swift crag
#

an overlay canvas doesn't really exist in the game world

#

press F with the canvas selected to focus your view on it

#

each pixel on the canvas is one unit in the scene view

#

so it's very big

summer stump
swift crag
#

for example, if the element should be in the top left corner, pick this anchor preset

#

this will let you position the element relative to that corner

#

so as the screen size changes, it moves around correctly

summer stump
scarlet skiff
#

dang

#

i posted in code cuz i play it via code šŸ¤” maybe in animation better yea

swift crag
#

I forget if Play() does any cross-fading

#

I wonder if you're just seeing the animation blend

scarlet skiff
swift crag
#

Set the state to 0x speed and see how it looks

scarlet skiff
scarlet skiff
swift crag
#

I just can't remember if Play() does a little crossfade

scarlet skiff
#

but maybe i can use crossfade and set the fade speed or wtv to 0

swift crag
#

i'm struggling to parse this part of the docs

#

If the transition from one state switches to another, it may or may not be blended. If the transition starts at 0.75 it will be blended with the other state. If no transition is set up then Play will continue to 1.0 with no changes.

#

i would try a 0-duration crossfade, yeah

scarlet skiff
#

may or may not
😭 ā“

swift crag
#

I haven't used the animator much recently so I don't have practical experience here

swift crag
scarlet skiff
#

animator.CrossFade("PlayerCrouch", 0, 1, 1);

#

should be what i need i think

tranquil radish
#

hey guys, im new to Unity and I was wondering why this code isnt working, i keep getting the error: NullReferenceException: Object reference not set to an instance of an object. Any help is apriciated, manny thanks :)

{
    public const int PlayerHealth = 50;

    public PlayerCls Player1 = new PlayerCls(PlayerHealth);
    public PlayerCls Player2 = new PlayerCls(PlayerHealth);

    public UI ui;

    void Start()
    {
        Player1.Health--;
        ui = new UI(Player1, Player2);
    }

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

    }


    public void OnHit()
    {
        print("Hit");
    }

    public void OnStand()
    {
        print("Stand");
    }
}```

```public class UI : MonoBehaviour
{
    public Text Player1Health;
    public Text Player1Points;
    public Text Player1Hand;

    public Text Player2Health;
    public Text Player2Points;
    public Text Player2Hand;

    public Text Nararator;
    
    public PlayerCls Player1;
    public PlayerCls Player2;

    public UI(PlayerCls player1, PlayerCls player2)
    {
        Player1 = player1;
        Player2 = player2;
    }


    private void Start()
    {
        Player1Health.text = "asd";
        print(Player1.Health);
        //Player1Health.text = (Player1.Health).ToString();
    }

    private void Update()
    {
       // UI_UpdatePlayerHealth();
    }

    public void UI_UpdatePlayerHealth()
    {
      //  Player1Health.text = (Player1.Health).ToString();
    }
}```
scarlet skiff
tranquil radish
scarlet skiff
#

print(Player1.Health);

Print is using when coding in unity?

tranquil radish
scarlet skiff
#

if you want text to show up

#

as ui

#

you create an object in ur scene that is of the type text

scarlet skiff
#

so Text myText

tranquil radish
#

i have already done that

scarlet skiff
#

then you change it by myText.text = "text here"

rich adder
#

thats declaring not assigning

tranquil radish
scarlet skiff
#

this is assigning

rich adder
scarlet skiff
#

but there still might be one missing

rich adder
#

if its assigned then you have a copy with it unassigned

scarlet skiff
#

a private variable that u maybe missed

rich adder
#

instead of guessing look at the line number of error

tranquil radish
#

yes i know why its being caused, but i dont know exsactly for what reason it is being caused

scarlet skiff
#

ngl that didnt make a whole lot of sense

#

but ye what line was the error

tranquil radish
#

i made a construcor in my calss, but after i initialise it the value is not asssignet / stays null

scarlet skiff
rich adder
#

monobehaviour should not have constructors

tranquil radish
#

or am i doing it wrong

scarlet skiff
#

you use instantiate

rich adder
#

yeah this is all sort s of wrong

scarlet skiff
#

if i understood correctly

tranquil radish
#

i only learned c# up to this point so i dont know hihi

scarlet skiff
rich adder
tranquil radish
#

hmm. what is best practice to do then?

rich adder
#

You can still do it on regular classes, just not ones that inherit Object

abstract finch
#
    {
        Vector3 directionToTarget = (_blackBoard.TargetPos - _turretPivot.position).normalized;
        Quaternion newRot = Quaternion.Slerp(_currentRotation, Quaternion.LookRotation(directionToTarget), (_state == State.Default ? _lookAtRotationSharpness : _shootingRotationSharpness) * Time.deltaTime);
        _turretPivot.rotation = newRot;
        _currentRotation = _turretPivot.rotation;
    }```
At a glance what am I doing wrong here? I just need the object to look at the target. However, it's stopping when its looking to the side. I made sure that the model's forward is indeed on the Z axis when moving it
#

Whats currently happening is this, its stopping on the side

soft kernel
abstract finch
#

Its global

soft kernel
#

sorry, select the local. my bad

#

see if the direction changes

abstract finch
#

Same result, however I do notice something strange if this matters. When I move the pivot forward, the X axis changes instead of the Z

soft kernel
#

the z is the side that looking to the player, right?

#

so thats the forward of the object it self

#

you can change it with a 3D software like blender or easily add or subtract 90 to the direction before applying it

abstract finch
#

I see, how do I fix this? I can't really change the model

#

Got it

#

I also noticed this in the original script, since I didnt understand what it did I edited it out

#

Not sure if its useful or not

#

So what I need to do is create a variable called aimoffset and work off that

soft kernel
#

yes and add it after the Quaternion.LookRotation(directionToTarget)

abstract finch
soft kernel
abstract finch
#

v3

soft kernel
#

not sure if it will work

abstract finch
#

doesnt seem to be working

soft kernel
#

I guess you should change the script a bit

abstract finch
#

When you said add it after Quaternion.LookRotation(directionToTarget) do you mean adjust the transform after its applied?

#

I created an empty gameobject inside it and parented the pivot, rotated the parent to 90 degrees and it seems to fix it

soft kernel
soft kernel
#

write Quaternion.LookRotation(directionToTarget) * Quaternion.Euler(_pivotAimOffset) instead

#

the _pivotAimOffset will be a Vector3 offset in any direction you want

abstract finch
#

Its working now so whenever I want to do offsets I need to convert it to quaternion then multiply it?

devout spire
#

I'm trying to make it so that if you're pressing the sprint key and you aren't in throwing mode, it sends a message that says running. However, for some reason it just floods the console with the message indiscriminantly, regardless of if I'm even touching my keyboard. This seems so simple, how is this happening?

    {
        MyInput();
        SpeedControl();

        if(Input.GetKeyDown(sprint) && throwObject.GetComponent<ThrowManager>().readyToThrow == false);
        {
            Debug.Log("Running!");
        }
    }```
soft kernel
#

just create a vector3 and multiply with Quaternion.LookRotation(directionToTarget)

abstract finch
# soft kernel there is multiple ways to work with angles but I think this is best suited for y...

Its great thanks. I have another question in regards to using this though. Before I would calculate if a transform is facing another via if currentAngle < targetAngle. However, with this code the transform is no longer accurate in game. How would I be able to get the simulated transform.forward with the offset. I could just use transform.right to compensate too

    public static float GetAngle(this Transform source, Vector3 pos, bool ignoreY = true)
    {
        Vector3 dir = pos - source.position;
        Vector3 forward = source.forward;
        if (ignoreY)
        {
            dir.y = 0f;
            forward.y = 0f;
        }
        float angle = Vector3.Angle(dir, forward);
        return angle;
    }```
abstract finch
#

So basically, I want the turret to shoot when its facing the player. The code above is to get the angle from its forward position to the target. However, now that I'm using an offset to calculate when to stop the rotation the angle is innaccurate. Is there a way to somehow get the transform.forward with the applied offset?

soft kernel
#

Oh I see

#

it can't tell that it's aiming

abstract finch
#

Right well, its getting the angle but instead of 0 its 90. It might be as simple as doing -90 or checking the distance between the target angle and current\

teal viper
#

I don't know the whole context, but why isn't forward corresponding to the object forward..?

abstract finch
teal viper
#

Fix it

abstract finch
abstract finch
#

I could actually fix it in blender because its not rigged

teal viper
#

Then fix it.

#

Or at least parent it to an empty and adjust the rotation such that the parent is facing correctly

abstract finch
#

It does seem more simple to fix it I figure I could learn something by fixing it with code.

teal viper
#

No one does that

#

It's like adapting for incorrect way of doing things

#

You should fix the underlying cause instead of making workarounds

soft kernel
#

btw if you export the fbx file over the file which is in unity it will automatically change it in game too

#

so you won't need to assign anything again

teal viper
#

The code logic shouldn't cover for asset issues. That's a sure way to get more issues.

abstract finch
#

ok I fixed it its not perfect but it gets the job done.

indigo wagon
#

how would I go about creating an npc which is interactable but has tree decisions?

#

2d btw

rich adder
indigo wagon
#

Sorry just a quick question but do you know if you're able to have specific follow up choices based on the choice you made using ink?

rich adder
#

yes

native seal
#

does raw image or image require a canvas?

frosty hound
#

Yes

native seal
#

so a sprite renderer is required for ingame

frosty hound
#

They're all 'in game'

native seal
#

sorry, in world

frosty hound
#

If you mean the world, then not really. You can have world space canvases too.

native seal
#

like using textmeshpro

#

not ugui

#

can things on canvases respond to colliders with a rigidbody

#

basically im making item labels above items on the ground and I want them to collide so none are overlapping

frosty hound
#

TMPro has both world and canvas versions.

native seal
#

yes i know

#

i assumed to use colliders/rb2d you couldnt use a canvas

frosty hound
#

That doesn't make sense

#

You can put colliders and rigibodies on any object, if your canvas is achild of that, it will "move" with the object

#

(assuming it's a worldspace canvas)

native seal
#

i was imaging everything would be on the same object, but now I guess it makes sense for them each to be different canvases

radiant totem
#

so dumb question but i just started unity a couple hours ago and i got fps movement and everything working but colliders are just not and im unsure of what to do

summer stump
radiant totem
#

yep that does seem to be the problem

#

ill have to find a new movement controller to use and maybe thatll fix

hexed knot
#

I have tried about 10 different ways but I can't seem to figure out this Quaternion. I'm trying to instantiate a prefab (a fireball). I've got it spawning at the player location, but I'm trying to get the rotation of the fireball to match that of the player. everything i tried it either locks at 0 or 180. https://paste.ofcode.org/Eq9YArGd95ZVr86JK3xdgG

hoary rivet
#

I have what I guess is a security question. I believe this should be the right place to post. If I am writing saves to a JSON format, is this a major security risk? I don't care about people adding in items and stuff. I just ideally don't want files that look like saves to ruin people's computers if they download them and then use the game to load them.

summer stump
#

Also, don't use Find, and cache your references when you get them

indigo wagon
#

Can anyone see an issue with this code, it would work prior to me adding the float and if statement. If more code is required to understand please let me know

eternal needle
native seal
#

anyone have a suggestion on how to better handle item labels? right now i just have rigidbodies and colliders on them so they do not overlap, however when many stack, they all kind of push away slowly and it ends up looking bad. Is there anyway make them "push" more or is there a better alternative to this since I imagine its intensive for no reason

indigo wagon
eternal needle
#

add a debug and see if the code is even running, if it ever enters the if statement

indigo wagon
#

I was trying to make it so it would only work when the player is within it's radius

#

alr

#

yeah nah it ain't running it

eternal needle
hoary rivet
#

Doesn't Diablo have a thing that filters bad items and doesn't show them?

native seal
#

i don't want to hide anything

summer stump
indigo wagon
#

and it showed nothing

eternal needle
summer stump
indigo wagon
#

ah

summer stump
#

debug the actual values

summer stump
#

what is distance

native seal
#

i do not want to hide anything

indigo wagon
#

distance between the player and enemy

native seal
#

obviously there will be loot filters

summer stump
native seal
#

but for them to resolve instantly

#

not slowly push eachother away

hexed knot
indigo wagon
#

could the issue be that I did this in start rather than update

summer stump
summer stump
indigo wagon
#

Yep

#

see my issue

#

the fact it only checks once

#

I'm a dunce

summer stump
indigo wagon
summer stump
indigo wagon
#

maybe I did the area a tad small

summer stump
swift elbow
#

How dare you suggest that in my presence

indigo wagon
eternal needle
# native seal this is the goal

ah, if thats the goal then you'll not be able to rely on unity physics at all. I havent done anything similar but i believe a relevant topic is aabb test

native seal
eternal needle
native seal
#

hm, maybe i just keep the physics implementation for now, its not too bad when theres a few items

#

there is no way to make the rbs "push" faster?

#

like basically increase their timescale

eternal needle
#

having rb on UI is definitely questionable

native seal
indigo wagon
#

@summer stump sorry to bother you again but I kinda created a new issue where I can't seem to figure out how to slow the enemy down

hard lodge
#

I just made crappy movement!

eternal needle
native seal
#

yeah, thank you

summer stump
whole idol
native seal
whole idol
#

It seems like the propeller has an engine of its own or something

summer stump
# whole idol

You have two translate calls in PlayerControllerX
You only update rotation of the propeller in Start

I find both of those things interesting, but likely not the issue

whole idol
#

Perhaps i shouldnt have made a new script for the propeller xD

summer stump
#

I did see the Player is scaled down to .5, but at least it was uniform. If there is a child between that and the propeller that is NOT scaled uniformly, that could definitely cause this issue

whole idol
summer stump
topaz mortar
#

I have a string with the name of one of my item prefabs in it, the string comes from my back-end
What's the cleanest way to access the prefab's fields (sprite) with only the name in a string available?
I have this:

    itemDrop.GetComponent<SpriteRenderer>().sprite = Currencies.Instance.Wood.Sprite;```
The problem here is that I need to write one of these lines for every item in my game that can drop.
summer stump
#

Then the only change you would need to make when adding a new item type is to add it to the dictionary without misspelling it

whole idol
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControllerX : MonoBehaviour
{
    public float constantFlyingSpeed;
    public float rotationSpeed;
    public float verticalInput;
    public float planeTurningSpeed;

    public GameObject propeller;

    private float propellerRotationSpeed = 10;


    void Start()
    {

    }

    void FixedUpdate()
    {
        verticalInput = Input.GetAxis("Horizontal");
        //this just flies forward like normal
        transform.Translate(Vector3.forward * constantFlyingSpeed);
        transform.Translate(new Vector3(0, verticalInput, 0));
        transform.Rotate(new Vector3(planeTurningSpeed, 0, 0));

        transform.Rotate(new Vector3(0, 0, propellerRotationSpeed));

    }
}

#

whats the error?

summer stump
whole idol
#

I know

summer stump
#

Also, screenshots would be better, as requested

whole idol
#

ok Ill do both

summer stump
# whole idol I know

Well, to help with that error (which should be your #1 priority), it would help to know which line is line 30

whole idol
#

Anyway here's a shortie from the actual gameplay

#

I assigned propeller here so now there's no error

#

at first it worked very well

#

but as I moved forward i completelly somehow kinda fucked it all up

#

and gradually got worse and more complicated šŸ˜„

#

But this is from the unity's official tutorial

summer stump
#

You are rotating around z every frame in your code
The second rotate call in FixedUpdate

whole idol
#

im following the assigenments they got there

#

ok good notice

#

Ill change that

#

At list now I dont got the weird random spins

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

public class PlayerControllerX : MonoBehaviour
{
    public float constantFlyingSpeed;
    public float rotationSpeed;
    public float verticalInput;
    public float planeTurningSpeed;

    public GameObject propeller;

    private float propellerRotationSpeed = 10;


    void Start()
    {

    }

    void FixedUpdate()
    {
        verticalInput = Input.GetAxis("Horizontal");
        //this just flies forward like normal
        transform.Translate(Vector3.forward * constantFlyingSpeed);
        transform.Translate(new Vector3(0, verticalInput, 0));
        transform.Rotate(new Vector3(planeTurningSpeed, 0, 0));

        transform.Rotate(new Vector3(planeTurningSpeed, 0, 0));

    }
}

#

now my question is.... how do i get to move the actual propeller lol

#

the goal is to move the plane up and down

#

while giving it rotation

#

and i tried to rotate it around game object placed on its nose

#

to look as if the propeller is doing the hard work

#

but couldn't do that because I had soooooo many random weird things breaking apart once i tried that

#

so I changed my mind and im like ok sure Ill keep rotating the plane around its center.

queen adder
#

Guys I'm creating an open world wild west game, right now I'm learning how to create basic fps controller because I'm new to the coding stuff when I'll be creating my proper 3rd controller for the game should I use animated controller like walk run idle animations or will I have to create something Procedurally generated I want to create a controller which can slide and have other good ragdoll effects like rdr1 or rdr2 so what should I do, I don't know much about animation and rigging other than unity animation controller basic stuff basically. Guide me on the right path so I don't regret it later

amber spruce
#

whats the best way to stop groups of enemies from grouping up and stuff

charred spoke
charred spoke
queen adder
#

So it's a combination of both ?

#

What's the easy way then

queen adder
cinder sorrel
#

Does unity support custom asset ?

vast crane
queen adder
queen adder
vast crane
#

I just wanted to ask does having cubes as buildings cause performance issues?

#

Someone told me it can cause performance issues

queen adder
#

Who told you that

cinder sorrel
vast crane
summer stump
queen adder
summer stump
queen adder
vast crane
summer stump
vast crane
#

I ned to call for it

summer stump
queen adder
#

Cube has only 12 triangles while a building has thousands

charred spoke
queen adder
queen adder
charred spoke
#

You can try but it’s not easy to use. In fact it does not work at all in modern unity

queen adder
charred spoke
#

We have been working on it and incorporating it into our motion matching system. So far it has taken 3 developers a total of 8 months to get it to a working state

queen adder
#

Oh man this thing sound way more complex than I thought

summer stump
#

3 devs that I assume already had extensive knowledge in programming and animation

charred spoke
queen adder
#

Should I just create an animated controller then ?

charred spoke
queen adder
#

2d blend tree whats that

summer stump
queen adder
#

Right now I have created a basic controller but it's moving in global axis if my controller is looking the other side and I press W it will go right or whatever the global direction is instead of moving forward even though in transform it's transform.localposition

summer stump
#

Use transform.forward

queen adder
#

Ok

cinder sorrel
#

It has embedded texture

queen adder
cinder sorrel
#

Yes

queen adder
#

i don't think it will why don't you import it ?

cinder sorrel
#

no I'm asking will unity support to read such files in game

summer stump
#

You can google supported file formats

cinder sorrel
#

I just don't want to expose the textures are .jpg and .BMP files

summer stump
#

Not really a beginner question

queen adder
#

why don't you use the normal formats ?

cinder sorrel
#

Well ..

#

Some third party tools can 1 click decompile your game

summer stump
#

Ah. No matter what format you use, they will still be able to do that

queen adder
#

bro don't care too much about that make a great game

summer stump
#

If the data is on their computer, they can decompile it

queen adder
#

we indie devs can't make great games if we focus too much on side quests

#

focus on the main quest

cinder sorrel
queen adder
#

you're priority should be

  1. player controller

  2. Enemy or AI System

  3. The World or Environment

  4. in Game Events

  5. some sort of idk property or shop system

  6. Inventory

  7. maybe a car or horse controller idk in which time you're game is set

  8. UI

#
  1. amazing Missions that feels unique
eternal needle
#

I missed the part where flappy bird had all of that

queen adder
#

not some mobile garbage even tough im creating a mobile game

frozen solar
#

Hello, i encountered a problem in my C# code saying me this :

Assets\Codes\Gestionmap.cs(64,33): error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

The error occurs in this line :

        int z = (int)Math.Round(biome.k + biome.amp * (Math.Cos(2 * Math.PI / 10 * biome.fx * x) + Math.Cos(2 * Math.PI / 10 * biome.fy * y)));

Someone know how to solve this ?

#

I think the problem is link with the Math librairy

silent vault
#

Instead, they use transform.TransformDirection(Vector3.forward);

#

What's the difference ?

teal viper
queen adder
#

guys my character is moving in global axis instead of local even tough im using transform.localposition and transform.forward just doesn't do anything the characters stops moving. i need help

#

btw my character does rotate in camera direction

teal viper
#

Use you own judgment and the actual API explanation.

teal viper
#

!code

eternal falconBOT
queen adder
#

the ` `` cs thing is not working for me i can't send

teal viper
#

Upload to a paste site then

queen adder
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine
;
using Unity.IO;
using UnityEngine.Accessibility;
using UnityEngine.Scripting;
using Unity.Multiplayer.Tools.NetStatsMonitor;
using Unity.VisualScripting;
using UnityEngine.Animations;
public class ThirdPersonControllerScript : MonoBehaviour
{
    private Vector3 location;
    [SerializeField] private int Speed;
    [SerializeField] private Animator Animation;



    private void Update()
    {
        // W FORWARD
        if (Input.GetKey(KeyCode.W))
        {
            location.z += Speed;
            transform.localPosition+= location * Time.deltaTime;
            Animation.Play("walking");
            location = location.normalized;

        }
        // S BACKWARD
        if (Input.GetKey(KeyCode.S))
        {
            location.z -= Speed;
            transform.localPosition += location * Time.deltaTime;
            transform.rotation = transform.localRotation;
            Animation.Play("walking");
            location = location.normalized;
        }
        // A RIGHT 
        if (Input.GetKey(KeyCode.A))
        {
            location.x -= Speed;
            transform.localPosition+= location * Time.deltaTime;
            transform.rotation = transform.localRotation;
            Animation.Play("walking");
            location = location.normalized;
        }
        // D LEFT
        if (Input.GetKey(KeyCode.D))
        {
            location.x += Speed;
            transform.localPosition += location * Time.deltaTime;
            transform.rotation = transform.localRotation ;
            Animation_.Play("walking");
            location = location.normalized;

        }

    }
}





#

ok now its working

#

hahaha

frozen solar
#

thank for the help, a last error occurs at the end of my code, and i dont understand how to fix that..

MissingMethodException: Constructor on type 'Gestionmap+Plaine' not found

But my class Plaine is defined like that :


 public class Plaine
 {
     public int k = 80;
     public int amp = 4;
     public double fx = 0.2;
     public double fy = 0.2;
     public int surface = 1;
     public double p_tree = 0.002;
     public int x { get; set; }
     public int y { get; set; }
     public double p_structure = 0.01;
     public int[] structures = new int[0];
     public int[] caves = new int[0];
     public double p_cave = 0.01;

     public Plaine()
     {

     }
 }

And the line of the error is this :

            object biomeInstance = Activator.CreateInstance(type, x, y);

Someone knows what to do ?

teal viper
queen adder
#

ohhh

#

so what should i do then

teal viper
#

Set transform position.

queen adder
#

transform.position ?

desert summit
#

so basically im making a game called "BUCKET" but i dont know what to do with it ive already gotten the movement and the first person any sugggestions?

#

also if u want the movement i have it

queen adder
#

still the same dlich

teal viper
# queen adder transform.position ?

Yes. Although, you'll need to transform your movement direction or use a world space direction like transform.forward. or use Translate.

Ideally, go through the beginner pathways on unity learn as this kind of basics are all covered.
!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

queen adder
#

im also using a camera wonder if thats causing the problem

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.IO;
public class ThirdPersonCamera : MonoBehaviour
{
    [SerializeField] float SensY;
    [SerializeField] float SensX;
    [SerializeField] private Transform PlayerRotation;


    private void Start()
    {
        // locked the cursor
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }
    private void Update()
    {
    float MouseX=Input.GetAxisRaw("Mouse X") * SensX * Time.deltaTime ; // Get X axis
    float MouseY = Input.GetAxisRaw("Mouse Y") *-1 *SensY *Time.deltaTime  ; // Get Y Axis
    PlayerRotation.localEulerAngles += new Vector3(MouseY,MouseX,0);




        Debug.Log(MouseY);
        Debug.Log(MouseX);
    }
}
teal viper
teal viper
frozen solar
#

you can read this ? the screenshot is tiny haha

teal viper
teal viper
#

Ah, you shared the line of the error

#

What's Activator?

frozen solar
#
            object biomeInstance = Activator.CreateInstance(type, x, y);
#

a way to create some instances i think

charred lodge
#
[System.Obsolete]
    private void OnCollisionEnter2D(Collision2D collision)
    {
        print("og");
        boomerangRain.gravityModifier = -0.73f;
    }```
frozen solar
#

thats the only solution i found to create instances of different classes

charred lodge
#

boomerangRain is particlesystem

gaunt ice
#

you can create instance by its class constructor
no idea why you use Activator, overkill

teal viper
frozen solar
silent vault
frozen solar
#

the variable type can refer to a lot of different classes

teal viper
#

Also, the error is probably due to incorrectly using the Activator. I don't see a constructor that takes 2 parameters.

frozen solar
#

i have a dictionnary of types, and the aim of this line is to take one of this types, and create an instance of it right after

#
foreach (string biomeType in typesTab)
{
    int x = rand.Next(0, n);
    int y = rand.Next(0, n);
    Type type = biomes[biomeType];
    object biomeInstance = typeof(type)(x, y);
    biomesTab.Add(biomeInstance);
}

return biomesTab;
teal viper
frozen solar
#

thats just that

charred lodge
frozen solar
#

  Dictionary<string, Type> biomes = new Dictionary<string, Type>();
  biomes.Add("Plaine", typeof(Plaine));
  biomes.Add("Foret", typeof(Foret));

charred lodge
#

function isnt working

frozen solar
teal viper
#

Instead of hardcoding your types biomes like that

frozen solar
#

okay but i need the constructors because a tuple (x,y) needs to be passed when i create the instances

#

so i make a dictionnary of objects ?

teal viper
#

Dictionary of SOs or objects of each biome type/factory of that type.

gaunt ice
#

enum+ switch case to create instance and return the reference to parent class

indigo wagon
#

anyone got a good way to create an npc that has different response options depending one the your previous choice?

gaunt ice
#

to prevent you misspell the class name and got key not found exception

frozen solar
#

what you mean with SOs ?

teal viper
teal viper
vast crane
#

hi someone please help! I made an animation but it doesn't show in unity play

hot lily
#

    public float calculateUnitTerminalVelocity()
    {
        float unitTerminalVelocity
            = Mathf.Sqrt((2 * unitMass * gravitationalAcceleration)/(dragCoefficient * airDensity * crossSectionArea));
            return unitTerminalVelocity; 
    }```
#

is it actually necessary to declare the public float unitTerminalVelocity above the calculation or it's fine not to?

ruby python
#

Well you're declaring it twice there. Both outside and inside 'calculateUnitTerminalVelocity' so the public will get overwritten every time.

hot lily
#

i assume the later one overwrites the value you mean

#

nvm i am idiot

hot palm
#

So I've read through this amazing article https://unity.com/how-to/naming-and-code-style-tips-c-scripting-unity
but was left wondering if I should use PascalCase or camelCase for private parameters, when I prefix them with an underscore, aswell as what you think / use / like better.

This

private int _Speed;
private bool _IsWalking;

or this

private int _speed;
private bool _isWalking;
gaunt ice
#

as long as it consistent, though i prefer _camalCase since you can use _PascalCase fro private methods now.....

hot palm
#

Well I posted it in unity talk and then realized this is a code question and I should probably ask in a code related channel :)

strong wren
#

šŸ‘ Note that you can delete messages or just indicate that the discussion has moved.

hot lily
#
    [SerializeField] private int _originalMaxEN = 100;```

I wrote this code but Unity doesn't display the numbers correctly (both showed up as zero), any reason why?
hot palm
#

Well someone answered there so deleting the message would have no point.
I first went to #archived-code-general bcs they suggested I ask there, posted it, then deleted it bcs this is a rather beginner question and then asked here. You know I didn't spam it, it was reasonable to leave and post it here aswell.
Thanks for reminding me of the guidelines, but I don't think I really cross-posted.

twilit cliff
atomic yew
#

I'm making an Offline RPG game in Unity. I want to save some things in my game. I have heard of two recording systems for this, one is PlayerPrefs and the other is to save in json format. PlayerPrefs is simple and easy to hack, and it does not work on all devices in json format. I do not consider the json format because it cannot be played on every device, and since the game is offline, I do not see any harm in doing it with PlayerPrefs. What do you think, what would be better for me to do?

hot palm
hot lily
#
    {
        get { return _originalMaxHP; }
        set { }
    }
    public int originalMaxEN //Allow access of the private integer OG Max EN
    {
        get { return _originalMaxHP; }
        set { }
    }```

I tried to extract the values into the editor panel but it doesn't work either
#

the integers OriginalMaxHP and OriginalMaxEN just don't show up entirely

hot lily
hot palm
charred spoke
hot lily
#

not sure what you mean

charred spoke
#

The deafult value is 0

#

If it was serialized before you did =100 the editor is simply doing its job and rembering the original default serialized value

#

Try hitting reset on your component and see if it changes to a 100

#

Or just adding the component to a new gameObject

atomic yew
strong wren
hot palm
hot lily
#

i still am unable to make the public version that uses an accessor to show up though

#

shouldn't the public accessor be visible on the editor?

hot palm
#

!code

eternal falconBOT
blissful spindle
hot palm
#

You should try to make it more readable

atomic yew
hot lily
charred spoke
hot lily
#

/die

hot palm
#

Np, good to see

hot palm
charred spoke
#

There is no need to serialize them

strong wren
blissful spindle
#

so the problem is that my Debug.DrawRay is not working as well as my Debug.Log can someone help me please?

hot palm
blissful spindle
hot palm
#
// Looks like this then
#

It is easier to comment on code, when being able to copy and paste it

atomic yew
hot palm
#

First of all consider using

hit.collider.CompareTag("Interactable")
atomic yew
blissful spindle
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Interaction : MonoBehaviour
{
    public RawImage interactionImage;

    void Start()
    {
        
    }

    void Update()
    {
        RayCastShoot();
    }

    private void RayCastShoot()
    {
        RaycastHit hit;

        Vector3 forward = transform.TransformDirection(Vector3.forward);

        if(Physics.Raycast(transform.position, forward, out hit, 2.2f))
        {
            Debug.DrawRay(transform.position, forward * 10f, Color.green);

            if (hit.collider.gameObject.tag == "Interactable")
            {
                Debug.Log("object that was hit: " + hit.collider.gameObject.tag);
                interactionImage.enabled = true;
            }
            else interactionImage.enabled = false;
        }
        else Debug.DrawRay(transform.position, forward * 10f, Color.red);
    }
}
hot palm
#

Yes now this is good

blissful spindle
hot palm
#

(If it gets any longer you can use !code to paste the code on the website and share the website link)

eternal falconBOT
hot palm
#

Bcs it's not foldable and lorge code blocks obstruct the chat

blissful spindle
hot palm
#

When you have to scroll to see other messages I'd say xD

blissful spindle
hot palm
#

Oh wait you do

blissful spindle
hot palm
#

Just do it regardless of if it does

#

Oh I see you want it red or green

#

Too fast to judge then, thats nice (if it works)

#

But you dont see the ray at all?

blissful spindle
blissful spindle
hot palm
#

try writing transform.forward

blissful spindle
lavish magnet
#

Hello all. This is a little game i'm making. The red bvox on the left is the score for what you just played. As you play more turns, i want the scores to kind of log themselves on the screen, and eventually look like this. Obviously with the different values and numbers from each play and etc and alligned correctly, Should i do this with an array and list? And howso? Im very lost.

hot palm
# blissful spindle ok

Do basic trouble shooting. Try displaying a simple ray. If that works, try to change the parameters to fit your needs

lavish magnet
#

Should i instnatiate and move it down by a certain amoount everytime? or is their like some sort of fill in system i can use

hot palm
#

Also disabling Gizmos in the scene view will make rays not be drawn

blissful spindle
blissful spindle
hot palm
blissful spindle
hot palm
hot palm
lavish magnet
blissful spindle
hot palm
hot palm
# lavish magnet Instead of rather Instantiation?

I mean what you like. If you want to instantiate, you would need to keep an array of positions where you instantiate it. It's way simpler to just make them in the scene view, disabling them and then activating them at runtime if needed

willow scroll
#

@lavish magnet (And don't forget to use a Layout Group)

willow scroll
hot palm
#

Wow I did NOT know that exists, but it's quite handy

willow scroll
hot palm
#

yup

#

Bcs it's not shown in the UI- Tab

willow scroll
#

Well, did you use to align everything manually?

hot palm
#

Yeah I anchored and positioned everything manually

oblique herald
#

Ive encounter a problem, where I am trying to pick up an item on the floor when I collide with it (still figuring out how to use interactive so im just starting from collision), and this error shows every time i hit the object:

NullReferenceException: Object reference not set to an instance of an object
Item.OnCollisionEnter2D (UnityEngine.Collision2D collision) (at Assets/Script/Item.cs:24)

where line 24 is:

inventoryManager.AddItem(itemName, quantity, sprite);

anyone know how to fix this?

hot palm
#

itemName is probably not known

lavish magnet
#

is inventoryManager referenced?

hot palm
#

or that

willow scroll
oblique herald
hot palm
#

np

spiral narwhal
#

Whoa, a new discord code block font :D
Looking sharp

hot palm
#

NullRefs are the most common error to have and I know they can be very mindnumbing haha

willow scroll
#

As we haven't seen the AddItem method yet

#

Please, check them all for being null

hot palm
oblique herald
#
    public void AddItem(string itemName, int quantity, Sprite itemSprite) {
        Debug.Log("itemName = " + itemName + "quantity = " + quantity + "itemSprite = " + itemSprite);
    }
lavish magnet
oblique herald
#

this is the additem

lavish magnet
#

D:

hot palm
willow scroll
#

They have a reference for the class, which should be written in thisCase

hot palm
#

Ah true

willow scroll
#
MyClass myClass;
hot palm
#

We are both right then

#

xD

#

The class should be PascalCase, the reference not

willow scroll
#

But you're right if it was MyClass.AddItem, where AddItem is a static method

hot palm
#

Yeah my bad, was working with static events too much xD

#

I distrust Singletons after my last game jam

willow scroll
#

The intentoryManager is thus null

#

How do you assign it?

hot palm
#

Maybe in awake which is not good?

willow scroll
#

They are quity useful if done correctly

spare umbra
#

Input is not working for some reason

hot palm
#

Yeah I am using them

willow scroll
spare umbra
hot palm
#

But I rather use events or Actions than Class.Instance.Method now

#

You have to subscribe to the action

#

Let me write down how

willow scroll
# spare umbra

Please, consider writing the full problem in a single message

willow scroll
spare umbra
#

Update

willow scroll
# spare umbra Update

I have mentioned it, that's why I asked to write the full issue in a single message

willow scroll
oblique herald
spare umbra
#

But the input values are never changing

#

always 0

hot palm
willow scroll
hot palm
#

Just wait a sec

oblique herald
#

oh uh here

    void start() {
        inventoryManager = GameObject.Find("InventoryCanvas").GetComponent<InventoryManager>();
    }
willow scroll
hot palm
# spare umbra Here, I'm using it to move my player

You have to subscribe to input actions like this

private InputActions _inputActions;


private void OnEnable()
{
    _inputActions ??= new();

    _inputActions.Player.Roll += DoRoll;

    _inputActions.Player.Roll.Enable();
}

private void OnDisable()
{
    _inputActions.Player.Roll -= DoRoll;

    _inputActions.Player.Roll.Enable();
}

private void DoRoll(InputActions.CallbackContext context)
{
    Vector2 inputVector = context.ReadValue<Vector2>();
    ...
}
spare umbra
#

@willow scroll @hot palm Oh it seems like I forgot to add theese :D

hot palm
#

Yep

spare umbra
hot palm
oblique herald
#

and yes i don't get an error there

hot palm
willow scroll
willow scroll
hot palm
#

Well that makes it easier if this works aswell

spare umbra
willow scroll
# spare umbra Here, I'm using it to move my player

In this case you call the method GetMoveInput twice in Update, which gets the same result and is thus redundant. Consider calling it once and storing the result into a variable.

void Update()
{
    Vector2 moveInput = InputManager.Instance.GetMoveVector();

    moveVector = new(moveInput.x, moveVector.y, moveInput.y);
}
willow scroll
hot lily
#

is PlayerInputActions still a thing?

hot palm
#

What else would be?

willow scroll
# oblique herald you mean this?

I am not asking about the InventoryMenu field's assignment. I want you to show me the reference to the InventoryManager you've shown in the image

oblique herald
#

this I assume... right? 😦

hot palm
#

The class where you call AddItem from

frigid sequoia
#

If want my player to tp back to the latest safe place after falling to a pit, what is the best way to do it? Do I send I Raycast down each frame and check if they are on solid ground to save that point at latest save point or...? Is there something sorta of stipulated for this?

hot palm
#

Depends on the environment, other methods are easier if it's for example blocky tiles. Then you could raycast downwards, check for layer "safe ground" and store that in a list

willow scroll
hot palm
hot palm
#

Then after falling down, I tp'd him back to the oldest safed place

#

I like Lists more than arrays

#

I add a vector3 position every second

#

and if it's above 30 I remove at index 0 and add the latest position

oblique herald
# willow scroll No, I want you to send me the class which references your `InventoryManager` scr...

sorry for the trouble, I think youre referring to this:

public class Item : MonoBehaviour
{
    [SerializeField] 
    public string itemName;

    [SerializeField] 
    public int quantity;

    [SerializeField] 
    public Sprite sprite;

    private InventoryManager inventoryManager;

    void start() {
        inventoryManager = GameObject.Find("InventoryCanvas").GetComponent<InventoryManager>();
    }

    private void OnCollisionEnter2D(Collision2D collision) {
        if (collision.gameObject.tag == "Player") {
            inventoryManager.AddItem(itemName, quantity, sprite);
            Destroy(gameObject);
        }
    }
}
hot palm
#

Yeah thsts the problem

#

Also SerializeField the inventory manager and assign it in the editor

#

GameObject.Find is just bad

#

Bcs if you rename the object you never know this script wont work

#

Also it should be

void Start()
oblique herald
#

cuz im literally jsut followin a yt vid for this and its like a years behind

#

plus i only am a 2 days old c# user :/

hot palm
#

It's alright

#

Just know that GameObject.Find is bad

#

Also the problem here is the

void start()

as unity doesn't recognize it as the start method and won't call it at the start

#

Getting Large and lower case right is important

oblique herald
#

that was totally the problem... i feel really dumb now

hot palm
#

After 2 years I still make silly mistakes, it's normal

#

It's always good to go get some fresh air and come back

willow scroll
#

Do Unity developers even get some fresh air?

hot palm
#

Idk about you but my brain doesn't function without fresh air

willow scroll
#

Alright, you definitely seem more normal than me

hot palm
#

Normal

frigid sequoia
hot palm
#

I had a weird terrain, so I wanted to tp back 30 iterations

willow scroll
frigid sequoia
hot palm
#

Problem is I had slopes you could slide down, not go up but can jump down

#

the slope end was above 100

willow scroll
# frigid sequoia Then just don't save it

You didn't seem to understand. What if the position was safe at the moment of saving it, but not it's not safe anymore? If you may have this sort of case, you'll probably want to have a list instead of a single variable.

hot palm
#

So jumping down would get you back to a safe and correct position

frigid sequoia
willow scroll
hot palm
#

Then have spawn points and make the player respawn/tp there

#

xD

#

tru

scarlet skiff
#

anyone knows any ways to detect which side of the collider an object has collided with? im trying do like a mario stomp on enemies typa thing, but i cant find any good tutorials

hot palm
#

For a minecraft prototype I had every block cast 6 rays and dont render the face of the block a raycat would intersect a collider

#

(had 6 colliders)

frigid sequoia
hot palm
#

So in 2d you would want 4 colliders, 1 for each side

#

I think it's maybe tedious to set up but you can do more stuff afterwards

#

Also prefabs>>

hot palm
hot palm
willow scroll
#

Although the logic for using a list won't be that much harder than with a single variable

uncut shoal
#

I have a list of a class, and it also contains classes that inherit from that class, how do I check if its a class that inherits from it

#

eg.

#

List<Element> elements = new List<Element>();

#

and it contains ObjectElement which inherits from Element

north kiln
#

loop over the list and check element is ObjectElement

#

The collection itself has nothing to do with it

uncut shoal
#

ok

next haven
#

if i change a value (like SubEntityData) inside originalProfile, will it also change the one inside blackboard.AttackProfile

#

like, is originalProfile an exact copy, or does changing it also change the place i got it from

ivory bobcat
#

Do you've got any errors?

oblique herald
#

nope

ivory bobcat
#

Nothing wrong with the code. Your problem is likely something else (script not compiling/updating for some reason)

hexed terrace
#

right mouse the script -> reimport

ivory bobcat
#

That doesn't look like the inspector for this script btw

#

Can you show the entire class?

#

Is it the Item class?

cosmic dagger
#

did you save the script?

#

it does look like a different class though . . .

oblique herald
#

wait

ivory bobcat
#

The code isn't what's shown in the inspector

oblique herald
#

i imported the wrong code file... so sorry guys :L

tough cave
#

How come the functions are not showing in inspector events? Am i missing something

public class PlayerController : MonoBehaviour
{
    private Rigidbody rb;
    public float speed;
    public UnityEvent onVictory;



    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    public void Move(Vector3 movement)
    {
        rb.velocity = movement * speed;
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag("Victory"))// enemy
        {
            onVictory.Invoke();
        }
    }

...
public class UIManager : MonoBehaviour
{
    public TMP_Text victory;
    public TMP_Text gameOver;
    // Start is called before the first frame update
    void Start()
    {
        victory.gameObject.SetActive(false);
        gameOver.gameObject.SetActive(false);   
    }

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

    public void ShowVictory()
    {
        victory.gameObject.SetActive(true);
    }

    public void ShowGameOver()
    {
        gameOver.gameObject.SetActive(true);
    }
ivory bobcat
#

Did you reference an instance?

#

If you're referencing the class script the instance methods will not be visible

tough cave
#

Oh. so you always need to reference to the gameObject that contains the script, rather than link it straight to the script. always.

cinder crag
#

why doestn my particle system show up? even tho im instiatiing it

#

i have a suspicion that its cause of this

fickle plume
#

Where do you start playing it?

cinder crag
#

in here im instantiating it , for the guy im following the tutorial works fine but for me doesnt seem to work

fickle plume
#

It's not set to play on instantiation, you need to actually start playing it

cinder crag
swift crag
#

reference your prefab as as ParticleSystem

fickle plume
#

You can instantiate it as its type and get reference directly

swift crag
#

Instantiate returns whatever type you gave it.

fickle plume
#

Intantiate<ParticleSystem>

swift crag
#

If the type is a component type (like ParticleSystem), it copies the entire object the component is attached to

fickle plume
#

yea, implicit is fine too

swift crag
#

the object parameter is T in the generic version of the function

#
Instantiate<ParticleSystem>(gameObject);

this is a compile error.

fickle plume
#

i see yea, there's a screen with prefab reference

swift crag
#

they're all GameObject-typed

cinder crag
#

wait how can i reference my prefab as an particle system ?

swift crag
#

by changing the type of the variable from GameObject to ParticleSystem

#

You will then need to re-assign the prefab reference.

#

The serialized data will still point to the prefab's game object.

#

When you drag the prefab back in, you'll serialize a reference to the prefab's ParticleSystem

fickle plume
#

Alternatively you can set particle system to play on instantiation in properties. But this way would be more of a learning opportunity

queen adder
#

guys i just watched a video on how to detect collision and that thing is working good but how do i detect if the object is not colliding the ! is not working.

#

im working on a shop system like red dead 2

cinder crag
queen adder
#

that's why i need that

#

ok

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.IO;
using System;
public class ShowMenuBook : MonoBehaviour
{
 

  
    public GameObject Canvas;


    private void Update()
    {
       

    }
    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Player")
        {
         Canvas.SetActive(true);
        }

        if (collision.gameObject==false)
        {
            Canvas.SetActive(false); // this is not working
        }
    }
}
#

the ! is also not working

cinder crag
#

and now i just this UnityChanThink

swift crag
ivory bobcat
cinder crag
swift crag
hot palm
#

You would use OnCollisionExit

queen adder
swift crag
queen adder
#

it means nothing

#

idk for experiment

hot palm
#

Yeah doesn't make sense

swift crag
#

valid (:

queen adder
#

to see if it works

swift crag
#

but you should think about what it does mean

#

Collision.gameObject is the game object that you interacted with in the collision.

hot palm
#

OnCollision is called, when something is colliding. So checking for no collision is interesting thinksmart xD

swift crag
#

A collision cannot occur without a game object because a collision must involve a collider, and a collider must be attached to a game object.

queen adder
#

yeah but how do i type collision.gameObject.tag == "Player" == false ? 🤣

queen adder
#

again i just learned

hot palm
#

When checking if something is leaving the collision, use OnCollisionExit

queen adder
#

like 5 minutes ago

swift crag
queen adder
#

ohh

swift crag
#

OnCollisionExit sounds appropriate

swift crag
#

i don't think i've ever used Instantiate with an explicit type parameter

cinder crag
#

this might work

swift crag
#

That sounds reasonable.

hot palm
#

Also don't do

collision.tag ==

Do this instead.

collision.CompareTag("Player")
raw aspen
#

Ive been trying to add this method to my player controller script but when i call it my player stays in the same position for some reason. any idea why ?

public void TeleportPlayer(Vector3 newPosition, Vector3 newEulerAngles)
{
    
    _controller.enabled = false;

    
    transform.position = newPosition;

    
    transform.eulerAngles = newEulerAngles;

    
    _controller.enabled = true;

    
    _verticalVelocity = 0f;

    
    Debug.Log($"player teleported to position {newPosition} and rotation {newEulerAngles}");
}
queen adder
#

its working

cinder crag
#

welp this error appears

queen adder
#

idk why im feeling this inner energy

swift crag
#

currentweapon.muzzleFlashParticles must be a ParticleSystem

ivory bobcat
cinder crag
#

pain

hot palm
#

Checking tags should look like this

if (collision.CompareTag("Player")) { ...; }
// Or
if (!collision.CompareTag("Player")) { ...; }
swift crag
#

CompareTag warns you if you use an invalid tag

queen adder
#

! doesn't work

swift crag
#

I believe it's also more efficient, but that is less important

ivory bobcat
hot palm
#

If ! doesn't work, something else is wrong

queen adder
#

nothing

swift crag
hot palm
#

It should return true, when using a valid tag, but not player

swift crag
#

Perhaps that's what caused this.

swift crag
# queen adder nothing

you need to actually do some debugging here. use Debug.Log to check the tag you're getting

hot palm
#

Also check for misspelling

#

Plaeyr and stuff

queen adder
#

i solved the problem so ?

queen adder
#

its working with fen method

cinder crag
hot palm
queen adder
swift crag
#

so you're attempting to play the particle system on the prefab

#

note that this wouldn't cause the error you saw

#

it's just also incorrect

cinder crag
#

oh damn

swift crag
#

also, you should check what currentweapon.muzzleFlashParticles actually is

swift crag
swift crag
#

now you're overwriting the prefab's particle system with the copy

#

oh wait, nvm

#

i cannot read

scarlet skiff
#

How do i destroy the parent and the children and not just the trampledHitbox?

queen adder
#

dalphat your method is a little rusty šŸ™‚

swift crag
#

Can you share the entire script, and also log currentweapon immediately before you try to instantiate its muzzle flash?

ivory bobcat
# cinder crag

The pattern would usually becs var particle = Instantiate(...); particle.Play();It looks like you're trying to play the particle of a prefab or the particle cloned

cinder crag
swift crag
#

I know. I’m wondering if the object stored in that variable still needs to have its particle system reference fixed.

#

I should say I need to see what currentweapon holds!

ivory bobcat
swift crag
#

And you’re still getting the error?

cinder crag
#

nope

queen adder
#

btw will offline inventory system be compatible with an online inventory system or do I have to create it from scratch ?

swift crag
hot palm
queen adder
#

like security and other stuff you know

#

btw what is an inventory fundamentally in unity some list ?

swift crag
#

multiplayer is an entire 55-gallon drum of worms

queen adder
hot palm
#

It's a class containing parameters such as a list

queen adder
#

i hope its not too hard šŸ™‚

hot palm
#

Depending on what you want it to do

swift crag
#

If you want to build something that's close to a multiplayer-ready system, just make sure that you separate the display of your inventory from the actual inventory data

cinder crag
queen adder
swift crag
#

the client would send instructions to the server to manipulate the inventory

#

this means the server can validate whatever the client is trying to do

hot palm
#

You could add an offline version which updates the server's version when going online again

swift crag
#

Inventory systems are already a major pain point, so I'd suggest just getting some experience with making any kind of working inventory first šŸ˜‰

hot palm
#

It's fun to prototype systems and it's easier to implement once they are fully fledged

queen adder
south mural
#
GameObject clonnedEngine = Instantiate<GameObject>(selectedEnginePrefab, enginePosition, Quaternion.identity);
currentEnginesForSendingToArray.Add(clonnedEngine);

can I create a list like this to store the clonned objects ?

queen adder
#

Btw how do I create the list ?

#

Show me a toturial and I'll watch it

hot palm
#

You have AI and Google, use it xD

#

Inventory unity

queen adder
#

I want the best toturial by you guys because you guys have the experience and I don't

hot palm
#

No I made my last one from scratch so I haven't really watched one lately. Just know that you can use scriptable objects as items

queen adder
#

99% of the unity toturials are faster than andrew Tate's Bugatti

cosmic dagger
hot palm
#

Well you will have to pause occasionally

queen adder
#

And they explain nothing

hot palm
#

As noone is answering this rn, I suggest you search it up and click through videos. Surely there are some good ones

#

Also I dont think it has to be unity specifically

cosmic dagger
south mural
cosmic dagger
#

there are a ton of them, and they do explain. you have to take the time to understand each line of code and what the intent for that type of inventory is. there are so many different versions of an inventory. you will never find one that fits all . . .

hot palm
#

Yeah it depends a lot on the type of inventory you want to make

cosmic dagger
south mural
#

I hope so

hot palm
#

I personally think lists are the better array, could be my limited knowledge tho

#

Being able to do List.Add and List.RemoveAt is just so good

cosmic dagger
south mural
hot palm
#

Only thing I can think of they're probably faster, as they are constant in size

south mural
#
    SerializeField] GameObject[] enginePrefabs;
    GameObject[] currentEngines;
    ParticleSystem[] currentEnginesPSystems;
    List<GameObject> currentEnginesForSendingToArray;
    List<ParticleSystem> currentEnginesPSystemsForSendingToArray;

    private void SetupEngines()
    {
        for(int i = 0; i < currentEnginesCodeline.Length; i++)
        {
            print(i);
            string currentCodeLine = currentEnginesCodeline[i];
            string[] mainSplit = currentCodeLine.Split('/');
            //mainSplit[0] location
            //mainSplit[1] engine type

            string[] locationSplit = mainSplit[0].Split(',');
            float x = float.Parse(locationSplit[0]);
            float y = float.Parse(locationSplit[1]);
            float z = float.Parse(locationSplit[2]);
            Vector3 enginePosition = new Vector3(x, y, z);

            int engineTypeNum = int.Parse(mainSplit[1]);
            GameObject selectedEnginePrefab = enginePrefabs[engineTypeNum];

            GameObject clonnedEngine = Instantiate<GameObject>(selectedEnginePrefab, enginePosition, Quaternion.identity);
            currentEnginesForSendingToArray.Add(clonnedEngine);

            currentEnginesPSystemsForSendingToArray.Add(clonnedEngine.GetComponent<ParticleSystem>());
        }
        currentEngines = currentEnginesForSendingToArray.ToArray();
        currentEnginesPSystems = currentEnginesPSystemsForSendingToArray.ToArray();
    }

why would this not work?

#

clonnedEngine returning null

hot palm
#

btw ur missing a [ at the beginning there

south mural
cosmic dagger
#

arrays are more performant because they have a set size and contiguous memory . . .

hot palm
#

Love me some uncommented code

south mural
#
        currentEnginesCodeline = new string[] {"1,1,1/0", "5,-2,1/0"};  
#

this is my codeline strings

#

but it still returns null

gaunt ice
#
private T[] _items;
```list is wrapper of array
unique idol
#

I have little problem with tilemaps and mouse positions

#

My localScale on tilemaps is 0.33

hot palm
#

why

unique idol
#

It's terraria like game, I had to change localScale to set player to be bigger than tiles

#

Or tiles to be smaller, like 3 tiles = player size

hot palm
#

It's always easier to rescale the player according to your world tho

cosmic dagger
hot palm
#

Well tell us your problem

#

Just commenting on what I've seen so far

hot palm
south mural
#
        for(int i = 0; i < currentEnginesPSystems.Length; i++)
        {
            currentEnginesPSystems[i].Play();
        }

I am using that arrays here when you press W. If you asking: You already have list, why you creating the almost same type array again? Can I use lists in this function too? I really don't know about lists.

unique idol
#

Okay, maybe it will be easier, I tried to rescale tilemap instead of player, and trying to make it fit in camera, but I forgot i can change camera distance šŸ™‚

#

Thanks @Tidali

languid spire
south mural
#

ohh let me try

#

but anyways why it is returning null object?

#

game clonning that object but can't add to a list?

hot palm
#

Only difference it's List.Count and Array.Length

hot palm
south mural
#
GameObject clonnedEngine = Instantiate(selectedEnginePrefab, enginePosition, Quaternion.identity);
currentEngines.Add(clonnedEngine);

game object clonnedEngine clonned successfully but in the second line, it giving nullreferenceexception

languid spire
hot palm
#

Maybe your list is faulty somehow?

gaunt ice
#

where you create your list

#

your list is null

ivory bobcat
south mural
south mural
#

out of start()

gaunt ice
#

btw dont need to use list since the length is known, unless you will add another gameobject later

ivory bobcat
languid spire
#
currentEngine = new GameObject[currentEnginesCodeline.Length];
for(int i = 0; i < currentEnginesCodeline.Length; i++)
        {
            ...
            GameObject clonnedEngine = Instantiate<GameObject>(selectedEnginePrefab, enginePosition, Quaternion.identity);
            currentEngine[i] = clonnedEngine;
   
        }
south mural
ivory bobcat
#

You'll need to initialize them before usage using the assignment operator =.

gaunt ice
#

read the above code stevesmith have written it for you

ivory bobcat
modest dust
ivory bobcat
#

Maybe consider what Steve is suggesting.

south mural
#
[SerializeField] GameObject[] enginePrefabs;
    GameObject[] currentEngines;
    ParticleSystem[] currentEnginesPSystems;

    private void SetupEngines()
    {
        currentEngines = new GameObject[currentEnginesCodelines.Length];
        currentEnginesPSystems = new ParticleSystem[currentEnginesCodelines.Length];
        for(int i = 0; i < currentEnginesCodelines.Length; i++)
        {
            print(i);
            string currentCodeLine = currentEnginesCodelines[i];
            string[] mainSplit = currentCodeLine.Split('/');
            //mainSplit[0] location
            //mainSplit[1] engine type

            string[] locationSplit = mainSplit[0].Split(',');
            float x = float.Parse(locationSplit[0]);
            float y = float.Parse(locationSplit[1]);
            float z = float.Parse(locationSplit[2]);
            Vector3 enginePosition = new Vector3(x, y, z);

            int engineTypeNum = int.Parse(mainSplit[1]);
            GameObject selectedEnginePrefab = enginePrefabs[engineTypeNum];

            print(enginePosition + " " + engineTypeNum);

            GameObject clonnedEngine = Instantiate(selectedEnginePrefab, enginePosition, Quaternion.identity);
            currentEngines[i] = clonnedEngine;

            currentEnginesPSystems[i] = clonnedEngine.GetComponent<ParticleSystem>();
        }
    }
#

this is my current code if you want to check out

swift elbow
#

How disgusting

south mural
languid spire
swift elbow
south mural
modest dust
swift elbow
#

Is this a dig at me?

languid spire
cinder crag
#

i am not sure how its getting disabled

ivory bobcat
hot palm
#

Maybe the prefab object is disabled

ivory bobcat
#

Is the audio source disabled?

hot palm
#

Is Unity disabled?

cinder crag
#

and i put the respective audio source of the gun prefabs here

willow scroll