#💻┃code-beginner

1 messages · Page 39 of 1

wintry quarry
#

Some invisible "lookpoint" object

ruby rivet
#

Hey guys, I´ve a question regarding tilemap. Why are the children of the tilemap not in order form bottom left to top right? Is there an option to enable sorting? If not, what would be the easiest way to achieve this?
Thanks

pine abyss
#

Hmmm... okay, yeah... thanks alot! And any idea how to make that object be a "crosshair" of sorts? So it would make kind of an FP "controller"? In another words... how would I mKe the look object stay "relative" in front of the character? Not by parenting, obviously
.... position + offset?

rich adder
#

so the order doesn't really matter, its all about when you drew/brush it in

short hazel
pine abyss
#

Thank you very much! You saved my evening ❤️

wintry quarry
pine abyss
#

🫶

ruby rivet
rich adder
round scaffold
#

Navarone what happened with the pfp with the beautiful hair

ruby python
#

Okay, in the right place this time.

I'm really confused about this raycasting thing. I've corrected my original code to use the correct way of raycasting. My control panel object is set to its own layer, but the raycast doesn't recognise it as it's own thing, it's returning the name of the 'Root' object. I'm very confused. lol.

    [SerializeField] Camera playerCamera;
    [SerializeField] int maxRaycastDistance;
    [SerializeField] LayerMask interactableLayerMask;

    private void Update()
    {
        RaycastHit hit;

        if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.TransformDirection(Vector3.forward), out hit, maxRaycastDistance, interactableLayerMask))
        {
            Debug.Log("I hit : " + hit.transform.gameObject.name);
        }
    }

It's been a while since I've done any interaction stuff, so seem to have forgotten a bunch.

wintry quarry
#

If there's a Rigidbody on the root object it will jump up and grab that

#

if you want the exact object you hit, use hit.collider

ruby python
#

Oh bloody hell, of course it is, thank you.

wintry quarry
#

hit.transform is a little too smart for its own good sometimes.

ruby python
#

Yeah, thanks though, one of those little things I forgot. lol.

slender sinew
ruby python
#

@slender sinew Ah cool. Thanks for that. 🙂

#

Next hurdle. (I know an interface is probably better for this, but I don't know anything about them at the moment, that's tomorrows homework. lol)

I have a script on my 'target' object that has a public method that switches a bool. How can I go about 'grabbing' that from the interact script and switching the bool? I know how to get a reference to a script, but as far as I know you need to know the name of the script?

slender sinew
#

yes, you do need to know the name of the script

#

and you are right that an interface is probably better

#

well that's precisely why an interface is better

ruby python
#

Yeah, it's too late and I'm too tired to learn about them tonight. lol.

slender sinew
#

if you had an interface such as IInteractable that had a method called Interact(), and your target object's script derived from that interface, your player interact script could run some simple code like

if (hitThing.TryGetComponent(out IInteractable interactable))
  interactable.Interact();
wintry quarry
#

Also I generally don't even use an interface. I just have a general purpose Interactable MonoBehaviour script that I just slap on any interactable object

#

You can give it a UnityEvent to actually define the behavior

#

e.g.

public class Interactable : MonoBehaviour {
  public UnityEvent OnInteract;

  public void Interact() {
    OnInteract.Invoke();
  }
}```
slender sinew
#

yeah the composition approach is probably best

ruby python
#

I'll be honest, I kinda glassed over a bit there. lol, long ass day. Just looking at the GetComponent/TryGetComponent stuff.

pine abyss
ruby python
#

@wintry quarry Okay I actually prefer the interactable class idea better. Just looking at the Unity Docs on the UnityEvents thing but not entirely sure where the 'OnInteract' behaviour is defined. Unity Docs don't seem to be helpful (or I'm missing it lol.)

wintry quarry
ruby python
#

Ooooooh, I get you.

wintry quarry
#

It will work just like how UI buttons work

#

or anything else with a UnityEvent

#

it can also be assigned at runtime with OnInteract.AddListener

ruby python
#

Gotcha, thanks, sorry running a bit slow atm. lol.

wintry quarry
#

no worries

pulsar glen
polar acorn
pulsar glen
polar acorn
ruby python
#

Thanks for the input guys, all very helpful 🙂

#

@wintry quarry Hope you don't mind dude, just want to be sure I'm getting this right. lol.

And then I grab a reference to the interactable script and trigger the Interaction() Method?

#

Yaaaaay, it works. lol. Thanks man, really appreciate it. 🙂 Very cool way of doing it too 🙂

wintry quarry
ruby python
#

Yeah, bizarrely simple.

#

Now that's working, I'm going to bed. lol.

queen adder
#

Whats wrong with the base.start and select entered?

cosmic dagger
#

i don't see any error for base.Start . . .

wintry quarry
#

also there's some other error above

#

that is cut off

#

= ga something has an error

polar acorn
cosmic dagger
queen adder
#

kk

wintry quarry
polar acorn
wintry quarry
#

missing semicolon.
assigning a GameObject value to a string variable
missing the entire rest of the function definition on line 21

cosmic dagger
#

Hmmm, I have an issue. I have an ObectPool<T> class that can recycle objects. When an object is recycled, it's appropriately despawned, reset (its state), and spawned again. However, the variable that referenced the object before recycling is still attached to the newly recycled object. How can I remove the variable reference when recycling?

eager elm
#

either with an event from the pool object that fires when it gets deactivated or you let the object that is referencing it handle the deactivation

queen adder
summer stump
#

Missing semicolon
Assigning gameObject to a string
Start isn't an override

eager elm
wintry quarry
#

is there an error?
What does the error say?

eager elm
#

I highly recommend not doing a XR game as your very first project

dry tendon
#

Heyy, hi everyone, does someone know if is there any way to use bloom just for a specific kind of objects? Cause I've applied it to all the scene... But i just wanna have it on lamps... not on the skybox. Im currently using a URP project

swift crag
#

you might be able to render the skybox separately and composite things together

#

alternatively, just make the lamps brighter and then adjust the bloom threshold

#

so that the sky isn't bloomed

wintry quarry
#

basically your lamps are too dim and/or your sky is too bright

swift crag
#

oh, this is code-beginner

#

i need a nap

dry tendon
cosmic dagger
dry tendon
wintry quarry
#

Window -> Environment -> Lighting

dry tendon
swift crag
#

That will adjust how intense the light from the skybox texture is

#

you might turn down the exposure, then turn up the Intensity Multiplier on the environment lighting

#

that will let you make the sky darker whilst still providing the same ambient light

wintry quarry
#

if you have a specific problem with it you can post the details here and get help #854851968446365696

#

you'll have to explain how it's supposed to work and in what way it's broken.

swift crag
#

"it doesn't work" does not tell us anything

#

since you're, presumably, here because it doesn't work

primal swift
#

if i use .normalized on a vector it should only return 1,0 or -1 ? Cause i keep normalizing my vector and getting weird numbers

wintry quarry
#

but the individual x, y, z components of that vector can and will have any values between -1 and 1

#

for example (~.7808, .~7808, 0) is roughy a normalized vector

#

what happened to the one you shared a few minutes ago?

primal swift
wintry quarry
#

if you only want horizontal or vertical directions that's a different story

primal swift
wintry quarry
#

wdym by "resets"?

swift crag
#

what even

#

well, i don't know about that game, but you often "reset" a game by just reloading the scene

wintry quarry
#

what the hell is sussys schoolgrounds

polar acorn
swift crag
#

this is not a mascot horror enthusiast server. you will have to explain what you want

primal swift
#

direction = (GameManager.mousePosition - transform.position).normalized; so this should return a normalized vector ?

primal swift
#

Well it doesnt :(

polar acorn
#

How do you know

wintry quarry
#

you just don't know what normalized means

primal swift
#

Debug.log

wintry quarry
polar acorn
wintry quarry
#

show the code and show the output

primal swift
#

` direction = (GameManager.mousePosition - transform.position).normalized;

    Debug.Log(direction);`
wintry quarry
#

and that printed what exactly?

wintry quarry
#

you have said this like 5 times

polar acorn
#

You've been sent the link to LoadScene

#

Just load the current scene again

primal swift
#

(0.24,-0.19,0)

pseudo sable
#

that's normalised

wintry quarry
#

it isn't but

wintry quarry
#

Also did you simplify the code from your script at all

primal swift
#

its the only debug.log i have

wintry quarry
#

because if the code is just what you said and it printed that, well I don't believe you

wintry quarry
polar acorn
# primal swift its the only debug.log i have
direction = (GameManager.mousePosition - transform.position).normalized;
Debug.Log($"Direction vector: {direction}, magnitude {direction.magnitude}");

Put this in and then show a screenshot of the log

wintry quarry
#

one of these vectors is probably a Vector2

#

so somewhere a z coordinate is getting lopped off

primal swift
wintry quarry
#

probably direction is a Vector2

#

and the other two are Vec3s

primal swift
#

direction is not a v2

#

its a v3 anyways i gotta go thank you tho ill bash my head against it later ahah

acoustic arch
#

if i reference a prefab, will it only be useful to instantiate it or can i use it to modify the same prefabs already in the scene

#

like for instance

#

can i make an array for all the item slot prefabs that are in the scene?

polar acorn
#

You can modify the prefab, which is not particularly useful

pseudo sable
#

changing a prefab at runtime won't update any instantiated versions of that prefab

acoustic arch
#

how do i reference all the slots in the inventory to then have the item icon in the slot be able to change

#

and put them in an array

#

or list

wintry quarry
polar acorn
tired axle
#

Heeey guys. I want to make a game where user will see figure and will try to draw something similar. Could someone point me some direction ?

wintry quarry
acoustic arch
#

the inventory slots already exist i just need to have them all in an array but i don't know how to reference them

wintry quarry
polar acorn
wintry quarry
#

select them all at once

#

drag the selection in

acoustic arch
#

ok

#

also

#

i know i can select many with ctrl

#

but how do i select a bunch all in 1 section

wintry quarry
#

Click the first

#

hold shift

#

click the last

acoustic arch
#

thanks

inner arrow
#

Is there a way to code shadow distance with URP?

devout flower
#

Not sure, but can't you just change the angle of the directional light?

inner arrow
#

It has a day and night system.

devout flower
#

Ah

#

Wait that's still possible

sudden quiver
#

so im trying to make sort of a Darksouls roll kinda thing. its top down 2D. how would i add force in the direction im moving?

devout flower
timid prawn
#

Hi! I'm not sure if I'm asking too much, but I've written a code to move a player in Unity using the "Input System" package. Everything works fine, but I've added a variable called "speed" to control the player's speed. However, my player remains very slow regardless of the value of the "speed" variable. If any of you could shed some light on the matter, I would greatly appreciate it.

rotund garnet
#

please send the c# script so i can look at it :)

timid prawn
#

all the script or just the line who called speed?

sour wren
#

Yo guys!! all fine? I'm trying to make the Rig in the car but when I play, I notice that the car's wheels don't move together with the wheel collider, how can I make the wheels move together with the wheel collider?

timid prawn
#

controller.Move(playerSpeed * Time.deltaTime); (this line is missing)

sour wren
timid prawn
#

I've included the most important lines for my issue; I've been grappling with this for 3 hours now. 😅

rotund garnet
#

maybe following a youtube video or looking on the web is you best bet

#

there are thousands of videos covering movement online

timid prawn
#

I did this by following a video x)

sour wren
#

Someone can help me pls?

polar acorn
eternal falconBOT
sour wren
#

I just wanna make my wheel follow the wheel collider

timid prawn
sour wren
timid prawn
rotund garnet
sour wren
# timid prawn "I would like to be able to

I'm trying to make the Rig in the car but when I play, I notice that the car's wheels don't move together with the wheel collider, how can I make the wheels move together with the wheel collider?

timid prawn
sour wren
polar acorn
sour wren
#

like the suspensions movement

eternal falconBOT
polar acorn
#

discord embedded text can't be searched

rotund garnet
timid prawn
#

like that ?test ?

polar acorn
timid prawn
#

let me 5 min to anderstand how it works ^^

timid prawn
polar acorn
#

You paste it, save it, and send the URL

timid prawn
polar acorn
timid prawn
polar acorn
timid prawn
swift crag
#

this is a single component in the inspector, yes.

timid prawn
#

ow, speed isnt the same here wow

polar acorn
swift crag
#

the field initializer in your script provides a default value, but unity remembers the values in the inspector

timid prawn
#

You solved an issue I've had for 2 hours, I didn't think to change it here! I've been modifying it in the script all along, updating it, I feel foolish!! thx

#

Why didn't changing the value in the script and refreshing update the value in Unity?

polar acorn
#

So it wouldn't make sense if they all used the default value in the script

random ether
#

Does anyone know why this isnt working? The object has a collider with is trigger on and the player also has a collider. Both have rigid bodies.

#

even this isnt working

rotund garnet
#

Have you made sure that the player game-object has the tag "Player" ?

#

by the way, if you are using 2D, then you have to write private void OnTriggerEnter2D(Collider2D other)

queen adder
#

click on it

rotund garnet
#

please provide the line 17 of the script

acoustic arch
#

i have an array for each inventory slot GameObject

#

and a List<> for the items in the inventory

#

but im not sure how to make the list of items inside of the inventory slots

vale mountain
#
        y = Input.GetAxisRaw("Vertical");

        sprinting = (x + y != 0);

        jumping = Input.GetButton("Jump");
        crouching = Input.GetKey(KeyCode.LeftControl);

        Debug.Log(sprinting);``` why is "sprinting" returning true when i dont press any of the horizontal or vertical axis buttons
misty vessel
#

Okay so im trying to make my car tilt whenever i turn, and i cant make it work. I thought about making an anchor point to the cars as a child but idk how to implement it
Code:

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

public class CarController : MonoBehaviour
{
    public float MoveSpeed = 50f; // Acceleration   
    public float MaxSpeed = 15f; // Max Speed
    public float Drag = 0.99f; // Friction
    public float SteerAngle = 20f; // Steering angle
    public float Traction = 1f;
    public float MaxTiltAngle = 25f;
    public float currentSteerAngle;
    public float rotateSpeed = 10f;
    [SerializeField]
    public GameObject TiltAnchor;

    public float curveAmount = 20.0f;

    private Vector3 MoveForce; // speed

    void Update()
    {
        //Moving
        MoveForce += transform.forward * MoveSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
        transform.position += MoveForce * Time.deltaTime;

        //Steering
        float steerInput = Input.GetAxis("Horizontal");
        transform.Rotate(Vector3.up * steerInput * MoveForce.magnitude * SteerAngle * Time.deltaTime);

        // Tilt
        currentSteerAngle = MaxTiltAngle * steerInput;
        if (currentSteerAngle < 0)
        {
            TiltAnchor.transform.localRotation = Quaternion.RotateTowards(TiltAnchor.transform.localRotation, Quaternion.Euler(0.0f, 0.0f, curveAmount), rotateSpeed * Time.deltaTime);
        }
        if (currentSteerAngle > 0)
        {
            Debug.Log("Tilting");
            TiltAnchor.transform.localRotation = Quaternion.RotateTowards(TiltAnchor.transform.localRotation, Quaternion.Euler(0.0f, 0.0f, -curveAmount), rotateSpeed * Time.deltaTime);
        }
        if (currentSteerAngle == 0)
        {
            TiltAnchor.transform.localRotation = Quaternion.RotateTowards(TiltAnchor.transform.localRotation, Quaternion.Euler(0.0f, 0.0f, 0.0f), rotateSpeed * Time.deltaTime);
        }
    }
}
vale mountain
timber tide
#

do you have reload scene stuck in update somewhere

swift crag
#

time to debug the logic that makes your scene reload.

#

determine what conditions must be met for it to happen

primal swift
#

direction = new Vector3(0.3f,-0.3f,0).normalized; direction should be (1,-1,0) but returns (0.71,-0.71,0). This cant be right ?

summer stump
#

Oh, this is the code from earlier

#

Yeah, don't do base.Start()
That makes no sense when inheriting from MonoBehaviour

MonoBehaviour DOES NOT HAVE a start method (as your error clearly states)

#

Also there are the other errors that have been pointed out twice

acoustic arch
#

https://hatebin.com/nvblciyaop
the item will show up in the slot of the inventory, but it replaces the item slot entirely with it even though in line 52 i had it use the child objects image

#

what did i do wrong?

tacit estuary
acoustic arch
acoustic arch
#

foreach (ItemData itemInInv in itemsInInventory) { var itemSlot = inventorySlots[5].GetComponentInChildren<Image>(); itemSlot.sprite = itemInInv.icon; //Here I will make the items in the inventory actually show up in their slots, inventorySlots array is the slots }

#

the item sprite appears in the parent object not the child's

#

im unsure what im doing wrong

swift crag
#

inventorySlots should be an array of a component that has a reference to the Image you want

#

i.e. an array of InventorySlot or something

#

also, GetComponentInChildren can get a component from the game object you called it on

#

It finds a component in the object or any of its children

#

Same deal for GetComponentInParent

acoustic arch
#

now it works fine

acoustic arch
#

how could i fix this?

swift crag
#

it'd also make your life easier later. you could ask an item slot what item it's holding, for example

tacit estuary
swift crag
#

you'll also need to show me what the problem is

#

i can't quite imagine this one

acoustic arch
#

but i replaced with something i made thats scaled correctly and its all good

#

https://hatebin.com/eplnieyoar - code
alright so everything from before works perfectly now, now how would i set which inventory slot the items go into, id want an item when added to go in the next open one from 0 -> 36

#

like

#

line 54

#

var itemSlot = inventorySlots[5].GetComponent<Image>();

#

i have in part of the script the inventory items list checks if the item being added fits or not

young warren
#

No . You use the debug.draw stuff. Look it up

astral basin
#

im trying to set i to true whenever a player switches to home scene, but i also want it to be true when they leave that scene, basically make the i = true outside of the if statement only if the if statement was true once, im a beginner sorry if this is silly, any help would be appriciated thanks

young warren
#

I don't understand your question btw.

astral basin
#

thanks though ill look it up

#

i havent thought about that

young warren
#

Usually if you're thinking "I want X when Y happens", you look up how to detect when Y happens, or how to make it happen

ashen ferry
#

u can subscribe to event instead of checking it in update I forgor which one tho one sec

swift crag
#

UnityEngine.SceneManagement.SceneManager.activeSceneChanged

#

that is the event you want

acoustic arch
#

public void ListItems() { foreach (ItemData itemInInv in itemsInInventory) { for (int i = 0; i < inventorySlots.Length; i++) //Checks for space in inventory { var itemSlot = inventorySlots[i].GetComponent<Image>(); itemSlot.sprite = itemInInv.icon; //Here I will make the items in the inventory actually show up in their slots, inventorySlots array is the slots } } }

#

currently a single item in the inventory fills every spot, due to the fact it enters a loop where its placed in each

#

how can i make it so that each itemInInv in ItemsInInventory enters the loop once

ashen ferry
#

break keyword ends the loop early if thats what u want

#

but you really just need one for loop I assume u gonna extend it into something that need second

drifting horizon
acoustic arch
#

but now

#

public void ListItems() { foreach (ItemData itemInInv in itemsInInventory) { for (int i = 0; i < inventorySlots.Length; i++) //Checks for space in inventory { if (inventorySlots[i].GetComponent<Image>() == null) //Slot is open { Debug.Log("Item Slot Open"); var itemSlot = inventorySlots[i].GetComponent<Image>(); itemSlot.sprite = itemInInv.icon; } else //Slot is taken { Debug.Log("Item Slot Taken"); continue; } } }

#

It always detects slots as being taken

#

even when their not

#

so it must be a logistics issue

ashen ferry
#

what ur doing here is checking if your inventory slot has image component and if it does it is taken

#

continue skips whatever is past it in a loop so it being the last statement is redundant

acoustic arch
#

oh

#

should i be checking for sprite then?

#

cause by default that's empty

#

expecting to be filled

ashen ferry
#

u should have some kind of bool or whatever to check if it is taken or not

timber tide
#

I wouldn't check for a sprite

ashen ferry
#

yea

acoustic arch
#

true, slot is open false, slot is full

#

how would i find out whether the slot is taken or not?

timber tide
#

is this a list or an array

ashen ferry
#

what is inventorySlots rn?

acoustic arch
#

it is an array

#

each element is an inventory slot

timber tide
#

So technically, if you have an index unoccupied, then it should just be null

acoustic arch
#

all elements are filled

ashen ferry
#

if you create array of like size 10 and dont set anything are indexes null? thats my question not to u btw kekW

acoustic arch
#

then the elements image is filled with the items sprite

timber tide
#

Ah, ok so you got a wrapper for the slots, and you populate the wrapper?

acoustic arch
#

yes

#

which is why it checked for sprite

timber tide
#

Sure, if it works for you. I don't see anything wrong with that.

acoustic arch
#

so it works but now a single item still fills in every single slot

#

it's better tho

#

a single item goes through the loop filling in every slot

timber tide
#

You need to break out of your loops once you detect an open slot you can fill

acoustic arch
#

it still causes one item to appear multiple times

#

even tho the loop should break

timber tide
#

you've two loops there. What's the outer loop for? I assume it was some subcontainer.

acoustic arch
#

the foreach is so every item in the inventory list goes through it

#

then for - is so that every item will take the next slot in the inventory

timber tide
#

Little confused. You've got a list for all items in your inventory, but you also have a reference to all slots that contain those items?

acoustic arch
#

list that contains every item in the inventory, so each element is the actual item (scriptable object) that has an icon

#

then an array that each element is the image where the item in the inventory will go

timber tide
#

Ah, ok so this is like loading a set of items into all your slots

acoustic arch
#

yeah a single item thats in the inventory going through the loop is filling every slot in the physical inventory

#

instead of breaking out like it should be

timber tide
#

Seems fine, debug what items you're inserting into the inventory is correct.

acoustic arch
#

what in the world

timber tide
#

oh wait let me think of this, gimmi a second. For loop inside of a foreach a little confusing.

acoustic arch
#

the single item in the inventory filled in like 20 out of 36 slots and stopped

timber tide
#

Well, for one, you reset the increment of the forloop everytime you break, meaning you have to go back to the start and check all the slots you just filled. But, it should still work assuming all the data you're putting into it is different.

acoustic arch
#

its random how many items fill in each slot

#

one time it was 14 - it never fills just 14 in anymore i tried testing it multiple times, always filled every slot

#

but now it just fills every slot everytime

timber tide
#

Well, what you have here should work. When you call ListItems(), it's taking whatever data is in itemsInInventory, then looping through each item in that container. In your forloop, it's checking for a slot, and when it finds a slot where there is a null sprite, it'll change that sprite to the current item then breaks. Repeat for next item; starting at the first inventory slot again.

acoustic arch
#

yeah i agree

#

im really confused whats wrong with ti

timber tide
#

start debugging the actual data you're inserting and not just by logging strings

acoustic arch
#

im gonna test to see if the invententory slots are all connected therefore changing with each other

#

ok i think that was the issue

#

nevermind i just made a dumb mistake

timber tide
#

Debug.Log(data)

acoustic arch
#

Debug.Log(i)

#

for example^

timber tide
#

you'd want to grab the current sprite data probably

#

otherwise it'll just continue to give you the type of object which is just the item

acoustic arch
#

yeah

acoustic arch
#

ive never done it before

timber tide
#

You are doing it there, but for just strings

acoustic arch
#

ive debugged like that

#

ye

timber tide
#
foreach (ItemData itemInInv in itemsInInventory)
{
  Debug.Log(itemInInv.icon);
}```
acoustic arch
#

oh

timber tide
#

think that gives the sprite name I think?

cosmic dagger
#

why is it named ItemsInInventory? isn't it just the Inventory? seems weird to see itemInInv and itemsInInventory. looks confusing, at least, to me . . .

acoustic arch
timber tide
#

seems like they're just loading their inventory with items

acoustic arch
#

each the same item

#

even though theres only 1 in the inventory

timber tide
#

Alright, so your data is the same

#

and you only have 1 inventory slot? lol

acoustic arch
#

no

#

1 item in the inventory's item list

#

and it ran the foreach (item in ItemsInInventory) enough times to act like it was in there 32 times

acoustic arch
#

ok so

#

i realized the issue wasnt from that

#

it was from when the inventory was opened

#

this is the menu opener

timber tide
#
 public GameObject[] inventorySlots = new GameObject[36]; //GameObject of each inventory slot```
#

How are you even getting an image component. I'm so confused.

acoustic arch
acoustic arch
#

it goes through a few hoops

#

anyways i basically just need a better place for the ListItems(); method to be run

timber tide
#

When you new this here, you're making a whole new set of naked GOs, and I'm not seeing where you're giving them images.

timber tide
#

gameobject

acoustic arch
#

var itemSlot = inventorySlots[i].GetComponent<Image>();
itemSlot.sprite = itemListInv.icon;

#

so idk what your confused abt

#

the slot gets the sprite of the item from

#

itemListinv.icon;

#

aka

#

the items scriptableobject "icon" field which contains a sprite

polar acorn
#

If you're just getting the image component from all of these objects that should be the type of your array

acoustic arch
#

i just dont know where to have my method that displays the item's in the inventory

polar acorn
acoustic arch
#

oh

ashen ferry
teal viper
ashen ferry
#

huh that worked

#

u normally get collection edited bs if thats the problem so didnt even check

#

ty

teal viper
ashen ferry
#

but then how I didnt get out of bounds or anything, I had normal for loop previously with same exact behaviour so I would definitely try get child which isnt there anymore

inner marsh
#
{
    [SerializeField] Transform EquipmentsParent;
    [SerializeField] EquipmentSlots[] EquipmentSlots;

    private void OnValidate()
    {   
        EquipmentSlots = EquipmentsParent.GetComponentsInChildren<EquipmentSlots>();
    }
}``` i dont understand what is wrong with this, can someone help?
gaunt ice
#

EquipmentsParent is null and you call getcomponentXX on it

inner marsh
#

wym?

summer stump
# inner marsh wym?

EquipmentsParent is null, as in nonexistent, or empty. There is no instance of an object assigned to it

Yet, you try to get the EquipmentSlots component from its children.

static cedar
#

It holds nothing.

#

So to speak.

inner marsh
#

would this not mean it works?

summer stump
#

Do you have more than one of that script?

#

Also, show that inspector again at runime if that is the inly copy of that script

queen adder
#

can someone help? usually when you move your mouse up and down, the camera rotates along the x axis but mine rotats along the z axis https://hatebin.com/dzucbktiqp

#

what is a good way to globally check if the keyboard focus is being captured by an input field?

warm lichen
#

This is kind if hard do explain, but does anyone know how to make a list that kind-of creates its own points as you unlock them? kind of like an inventory but instead of pictures its words. does that make sense or do i need to try and make a better explination

inner marsh
round scaffold
#

how would you make a for loop go down a list for some reason i cant find anything anywhere lol

#

unless i dumb

#

for some reason the for loop isnt able to go over 1

round scaffold
#

unreachable code

#

im not sure why

north kiln
#

you must be returning or breaking in every possible iteration of the loop

#

presumably, at the end of the loop outside of your screenshot

round scaffold
#

ah i see

#

thank u thinking cat

lethal depot
#

hey guys, i have this game called "It's Raining Cubes" in this i catch cubes falling from above . i want to count the score (how many cubes are falling between two platforms i) to do that i have created a empty game object and made it child of the platform game object , but now to count score i have to make a new gameobject called "GameManager"(with GameManager script attached to it) but i dont know how to access ScoreLine in GameManager script which is attached to a completely different object, any idea how i can access that object( collision of that object to count score). sorry the ScoreLIne object is child object of player parent object

ruby rivet
# rich adder np. what is it you're trying to do exactly?

Well I had another system where all the (tile) gameobjects where under a mapParent. They were in order from bottomLeft to topRight and therefore I could get them by mapParent.transform.GetChild(childIndex);
With tilemap that isn´t the case anymore. I want functions like:
public Transform GetTileGameObject(int childIndex) {}
public Vector2Int GetXYFromChildIndex(int childIndex) {}
public int GetNeighborChildIndex(int currentChildIndex, EMoveDirection eMoveDirection) {}

I´m completly new to tilemap. I saw how RuleTiles work and wanted to switch from my previous system.

Update: Got it working saving the childIndex (which I calculated) and then using the .Sort function.

grand lintel
#

hello i need help with an bug that is happening in my editor. In my script i initialize 4 lists and when i press play it moves objects in the list around (this is only seen in the inspector), however when i exit play mode 2 of the lists don't reset to their original values and one of them entirely disappears. I also get a reoccurring error. this happens until i press play again and it returns to the default values as it should and the errors disappear. NullReferenceException: SerializedObject of SerializedProperty has been Disposed.
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <a26505b064194c429b83f4a02cfddb4d>:0)

grand lintel
#

sorry what is a good bin site so i dont have to send screenshots

teal viper
#

!code

eternal falconBOT
weary crystal
#

Huh what is it now??

"error CS1504: Source file 'C:\Users\SuperNinja313\Documents\Unity Projects\Learn\Assets/Scripts/CodeNo1.cs' could not be opened -- The process cannot access the file 'C:\Users\SuperNinja313\Documents\Unity Projects\Learn\Assets\Scripts\CodeNo1.cs' because it is being used by another process."

grand lintel
teal viper
weary crystal
teal viper
grand lintel
weary crystal
# teal viper What file are you trying to access?

There's literally nothing in the code, I just created it.

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

public class CodeNo1 : MonoBehaviour
{
    public string firstName;
    public string lastName;
    private TextMeshProUGUI textEdit;

    // Start is called before the first frame update
    void Start()
    {
        textEdit = GetComponent<TextMeshProUGUI>();
        textEdit.text = $"Hello {firstName} {lastName}";
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
teal viper
teal viper
grand lintel
teal viper
#

Are you or are you not using any assets that add features to the editor? Like Odin inspector.

grand lintel
#

no im not just a brand new scene with those 2 scripts on a empty

ebon fox
#

can anyone help me with that error?
i dont really know why its there.

thats what causes the error:

foreach (GameObject claws in Photon.VR.Player.PlayerSpawner.playerTemp.transform)
            {
                if (claws.gameObject.tag == "ClawLeft")
                    clawsLeft.Add(claws.gameObject);
                if (claws.gameObject.tag == "ClawRight")
                    clawsRight.Add(claws.gameObject);
            }
teal viper
#

It's probably a unity ui bug. If it doesn't happen again, just ignore it.

weary crystal
teal viper
grand lintel
ebon fox
teal viper
teal viper
ebon fox
grand lintel
ebon fox
#

oh the Photonnetwork isnt the problem btw. i already debugged it

teal viper
# ebon fox

Is it configured properly? Take a screenshot of the whole window.

grand lintel
#

this is outside of playmode

#

this is inside

teal viper
# ebon fox

weirdly enough, It seems configured. Maybe because of the version? Looks old.

Anyways, the issue is that you try to iterate GameObjects in the foreach, but transform children are of Transform type.

ebon fox
teal viper
grand lintel
teal viper
teal viper
grand lintel
#

did you see my pictures

teal viper
grand lintel
#

hmmm maybe its the vertion of unity lagging

teal viper
grand lintel
ebon fox
teal viper
# grand lintel

Should be fine.

Can you remove the using Unity.VisualScripting; from one of your scripts?

grand lintel
#

ok

#

Didn't work

teal viper
#

Can you comment out your code in GameManagerS.Start?

grand lintel
#

but only if i remove all three

teal viper
grand lintel
#

its on the same object

#

as GM

#

randomCards is also fine (it still happened when i removed it)

teal viper
#

Can you reference it in the inspector instead of using the find function?

grand lintel
#

ok

#

didnt work

#

the only thing stoping it is removing MoveCards

teal viper
#

That's weird.

grand lintel
#

ikr

#

do you know anyone who could help?

teal viper
teal viper
ruby python
#

Mornin' all. First time doing this particular thing, so getting a bit lost. I've got an fps controller, and I'm trying to interact with a button on a world space UI. (camera is firing out a ray etc.) Could anyone point me in the right direction please?

sour fulcrum
#

Probably silly question, I have value that can sometimes be positive and sometimes be negative, how to I make it always positive?

grand lintel
teal viper
teal viper
grand lintel
#

NullReferenceException: SerializedObject of SerializedProperty has been Disposed.
UnityEditor.SerializedProperty.get_objectReferenceInstanceIDValue () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.EditorGUIUtility.ObjectContent (UnityEngine.Object obj, System.Type type, UnityEditor.SerializedProperty property, UnityEditor.EditorGUI+ObjectFieldValidator validator) (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.ObjectField+ObjectFieldDisplay.Update () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEditor.UIElements.ObjectField.UpdateDisplay () (at <35c0e5f206594d2fa707969117964d70>:0)
UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <b8c852c145a8456ba2512bf23f96ab0b>:0)
UnityEditor.RetainedMode.UpdateSchedulers () (at <a26505b064194c429b83f4a02cfddb4d>:0)

teal viper
# grand lintel

The first error we can work with probably. Share it's details.

#

And it's possible that it's causing the other errors too

grand lintel
#

ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List1[T].get_Item (System.Int32 index) (at <b89873cb176e44a995a4781c7487d410>:0) NameSpaceIGuess.MoveCards (System.Collections.Generic.List1[T] a, System.Collections.Generic.List1[T] b, System.Collections.Generic.List1[T] indexs) (at Assets/Scripts/NameSpaceIGuess.cs:23)
GameManagerS.Start () (at Assets/Scripts/GameManagerS.cs:34)

teal viper
#

Here:

    public void MoveCards(List<string> a, List<string> b, List<int> indexs)
    {
        for (int i = 0;i < indexs.Count;i++)
        {
            b.Add(a[indexs[i]]);
            a.Remove(a[indexs[i]]);
        }

    }

Make sure that a[indexs[i] is >= 0 and < a.Count.

rotund path
#

I'm trying to get a top-down shooter working and normally I would get it working with the old input system. But I can't seem to get it working this time for the new system. How can I fix it?

teal viper
grand lintel
#

so should i add Count/1

teal viper
#

You should make sure that the index that you use to access list a is within it's bounds.

teal viper
grand lintel
#

errors gone

teal viper
grand lintel
#

by errors i mean the range one not the stupid one

teal viper
rotund path
teal viper
grand lintel
grand lintel
teal viper
teal viper
grand lintel
#

yeah to good to be true

teal viper
#

Here's a tip:
step through your code on paper.
Specifically, with num here int num = Random.Range(0, outOF); being equal to list.Count - 1 twice in a row.

grand lintel
#

it seems to happen alot because it stopped it doing it if its negative and it only does it twice

teal viper
#

Honestly, there's no way it could be negative.

grand lintel
#

so unity is lagging again

teal viper
teal viper
#

in other words difference between current and previous frame

#

Though the values do look weird

#

Oh, you transform them

#

Try printing the raw value.
also, transforming it is not gonna help

grand lintel
teal viper
#

but it could be bigger or equal to your list count

rotund path
teal viper
grand lintel
#

by the time it moves cards to bothand it doesnt look like the list has updated it length

#

ok im gonna take a break thanks for trying for so long

teal viper
grand lintel
#

this is what i got... a.Remove(a[indexs[i - indexs.Count]]);

#

nvm that made it worse

gaunt ice
#

!code

eternal falconBOT
teal viper
grand lintel
#

bro sorry im trying i dont really know how i would clamp the index but i added outOF-- after i add num to cards

slow hollow
#

guys where should i get help for a script im codding

#

in which channel

charred spoke
#

If you have to ask I suppose it’s here

slow hollow
#

ok

#

Can someone help me i am not able to find the mistake using ```System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Testingscript : MonoBehaviour
{
public GameObject TriggeringObject;

private void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Player") && TriggeringObject != null)
    {
        Debug.Log("Trigger activated");
        // You can also perform other actions on the TriggeringObject here.
    }
}

} ``` this is my script i have checked the is trigger option to true in the inspector panel of TriggeringObject and also set the Player object tag To Player but still the "Trigger Activated" is not send to console. This script is attached to an empty Gameobject and i have also PLaced the Triggering object in the script

ruby python
#

Hmm, okay, I'm obviously missing something really obvious here. Could someone please take a look and point me in the right direction please? I have a couple of scripts, one that fires a ray out of the camera, and one that 'lives' on an interactable object that simply holds a string. The idea being that when the ray hits the object, the script 'grabs' the script holding the string and relays it to a hud element.

Raycast script ( in Update() )

        RaycastHit hit;

        if (Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, maxRaycastDistance, interactableLayerMask))
        {
            InteractionMessage interactionInstruction = hit.collider.gameObject.GetComponent<InteractionMessage>();
            interactionPrompt.text = interactionInstruction.messageToSend.ToString();

            if (Input.GetKeyDown(KeyCode.E)) {

                Interactable interaction = hit.collider.gameObject.GetComponent<Interactable>();
                interaction.Interaction();
                Debug.Log("pow");
            }
        }
        else
        {
            interactionPrompt.text = "";
        }

Message Script (on the 'target' object)

    [SerializeField] string interactionMessage;
    public string messageToSend;

    private void Start()
    {
        messageToSend = interactionMessage;
    }

Issue I'm having is that the raycast script doesn't seem to find the message script (or the string variable). (Null reference exception when the ray hits the target object)

charred spoke
#

The trigerring object reference you have does nothing here

slow hollow
charred spoke
#

Well no. The OnTriggerEnter message will be sent to the object with the trigger collider, not to a random empty object.

slow hollow
#

alright i guess i will do it simply instead of dealing with complex things

charred spoke
#

There is no complexity here

#

How would the system know to send the trigger enter msg to your empty game object when the trigger of another object is entered?

charred spoke
slow hollow
#

i am telling i would go with ur idea

charred spoke
ruby python
#

@charred spoke It's okay I just figured it out. I was being a moron and got my layers mixed up.

polar comet
#

I wrote a simple block of code for moving forwards with AddForce but for some reason instead of going forwards like it should do it's moving towards positive Z can someone tell me what's the issue ? here is the code : https://gdl.space/uyidoyedak.cpp

clear steppe
#

how do i make it so when i click on the tv with the button e, it activates the light in it ?

charred spoke
charred spoke
grand lintel
#

@teal viper i figured it out the unfixable bug

polar comet
clear steppe
charred spoke
#

AddForce(transform.forward*5)

charred spoke
polar comet
grand lintel
# teal viper What was it?

nothing to do with the code at all, it was a corrupt prefab file hiding in the scene. i figured it out when i started a new project with the same code and it worked.

polar comet
#

FINALLY WORKING COLLISIONS

grand lintel
vale mountain
frigid nimbus
vale mountain
#
    {
        if (!base.IsOwner)
            return;

        if (Input.GetKeyDown(shootKey) && canShoot)
            Debug.Log("Shoot");
            Shoot();
    }

    [ServerRpc]
    public void SpawnObjectServer(GameObject obj, Vector3 position)
    {
        GameObject spawned = Instantiate(obj, position, Quaternion.identity);
        ServerManager.Spawn(spawned);
    }

    [ServerRpc]
    public void DespawnAllShootParticles()
    {
        foreach(GameObject particles in GameObject.FindGameObjectsWithTag("ShootParticles"))
        {
            ServerManager.Despawn(particles);
        }
    }

    void Shoot()
    {
        ShootServer(damage, shootFrom.position, Camera.main.transform.forward);
        shoot.Play();
        ShootSoundServer();
        deagle.SetTrigger("Shoot");

        if (Physics.Raycast(shootFrom.position, Camera.main.transform.forward, out RaycastHit hit, Mathf.Infinity, playerLayer))
        {
            if (hit.transform.gameObject == this.gameObject) return;
            hitS.Play();
        }

        SpawnObjectServer(shootParticles, shootPoint.position);

        StartCoroutine(CanShootUpdater());
    }```
short hazel
#

brrrrrrrt
You also have an error in the console

vale mountain
#

yeah thats the one frame that the camera isnt assigned but it assigns it straight after so its fine

frigid nimbus
vale mountain
#

in the getkeydown

#

thing

short hazel
#

Ah it's this

if (Input.GetKeyDown(shootKey) && canShoot)
    Debug.Log("Shoot");
    Shoot();

If with no braces { } only take the next statement. So Shoot() is called each frame

#

Only the log is included in the if

vale mountain
#

oh yeah i forgot about that

#

it was happening before i put the debog log

#

debug log

#

but ill try again

#

because that could well be why

frigid nimbus
#

Also I wouldnt make the server spawn a gameobject each time a shoot is fired btw

vale mountain
#

how would i spawn particles for every player?

#

is there a better way

vale mountain
#

thanks for help

frigid nimbus
# vale mountain is there a better way

First you aren't deliting the gameobject and instantiating that many gameobject could cause perfomance and memory isues, you could use object pooling or maybe make that the gun itself has a child wich is the muzzleflash and send a RPC to make it play instead of instantiating a new game object

charred spoke
static cedar
vale mountain
frigid nimbus
vale mountain
#

handy i didnt know that

#

wait im using servermanager.despawn so i cant use destroy

frigid nimbus
#

but you have also to destroy it on all clients

vale mountain
#

ill just a coroutine

frigid nimbus
vale mountain
#

FishNet

frigid nimbus
vale mountain
#

if its not broken its working

frigid nimbus
polar comet
#

doesn't tranform have any definition for stuff like up, forward, back, left and right ?

#

my console is telling me it doesn't but it seems weird

delicate portal
#

How do I lerp materials? I tried material.lerp, but that doesnt seem to work correctly, since it doesnt change the material 100% to the second one

polar comet
# frigid nimbus yes it does

I'm getting errors anyway ( here is one of them ) : Assets\player scripts\PlayerMovement.cs(30,38): error CS1061: 'Transform' does not contain a definition for 'left' and no accessible extension method 'left' accepting a first argument of type 'Transform' could be found (are you missing a using directive or an assembly reference?)

frigid nimbus
#

i dont belive transform.left exists, only .up and .right

#

so if you want left you do transform.right * -1

#

or down transform.up * -1

polar comet
frigid nimbus
#

it works now?

polar comet
#

yeah I'm gonna try that out ty for the help

polar comet
# frigid nimbus it works now?

I tried to write defintions for left and right but it doesn't work and I've got errors now. Here are the lines :
Vector3 left = transform.right * -1; Vector3 back = transform.forward * -1;

clear steppe
#

i have a question how can I turn on something within a certain area like when i close to it, I can then activate it

#

cause now when i click e from any distance it turns on automatically

#

i want it so i'm within near the area i can activate it

lost hamlet
#

The easiest way would be using a trigger around your player, or checking the distance between you and the objects

#

Using the Trigger you can enable objects when they are inside and disable them when they are outside

clear steppe
#

how do i check the distance ?

polar comet
gusty gyro
#

Hello im a beginner at unity what can i use if i want LAN Multiplayer (2d Game)

short hazel
#

You learn Unity without any kind of multiplayer first. Adding a networking stack significantly complexifies the whole thing

lost marsh
#

@north kiln (`using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class cameraworks : MonoBehaviour {

[SerializeField] private Vector3 _offset;
[SerializeField] private Transform target;
[SerializeField] private float Smoothtime;
private Vector3 _currentvelocity = Vector3.zero;

private void Awake()
{
    _offset = transform.position - target.position;
}
private void LateUpdate()
{
    Vector3 _targetposition = target.position + _offset;
    transform.position = Vector3.SmoothDamp(transform.position, target.position,ref _currentvelocity ,Smoothtime);
}

} `)

north kiln
#

You are not using your target position variable

golden ermine
#

Hi everyone, I have an campfire prefab with this script attached to it: https://hastebin.com/share/xasaqaqebo.csharp in that script it says when player is inside of trigger of an campfire and he is pressing "E", and he has enough wood to make a campfire(woodCount >=3) it will make a campfire and it should take away 3 wood cause campfire costs 3 wood but the problem is it takes away for example i have 6 wood collected and i make a campfire it will take away all 6 woods for some reason. Can someone help me with that? This is script where I count wood: https://hastebin.com/share/zuyotiqici.csharp

sour fulcrum
#

your using OnTriggerStay, which means the code in that will happen every frame the player is inside that trigger. you probably want OnTriggerEnter instead

golden ermine
#

but then I need to click "E" exactly when I enter trigger right?

short hazel
#

You're taking the wood in OnTriggerStay. So if you get in range of the campfire and hold E for more than 0.02 seconds, it's going to take 6 wood items

#

3 wood each 0.02 seconds

#

You need a variable that stores whether the campfire was already lit, and don't light up the campfire again if it's the case

sour fulcrum
#

^, Also, If you didn't know, Input.GetKey is a thing, which just checks if it's being pressed that frame, and not if it was pressed for the first time that frame like GetKeyDown

golden ermine
#

inside campfire script?

short hazel
#

Of course

sour fulcrum
#

Input.GetKey is kinda the equivilent to OnTriggerStay if that makes sense

short hazel
#

private bool isLit; and then if (ePressed && !isLit)

#

If E is pressed and it's not lit yet

#

Then set isLit = true

golden ermine
lost marsh
kind wolf
#

my oculus quest 2 game is very laggy and i need help
I built it on my Quest 2 and its very laggy, i tried changing some settings and stuff but it dosent really work

short hazel
# golden ermine

The second if does not prevent the first one to be executed here. Code runs from top to bottom

golden ermine
#

it works now

sour fulcrum
golden ermine
#

but also when I press "E" and im inside of an box collider set to trigger in campfire prefab it doesnt always make a campfire its laggy i need to touch box collider thats not set to trigger, how can i fix that?

short hazel
#

Now you don't need the last if statement

golden ermine
#

okay i will remove it

kind wolf
sour fulcrum
#

Your computer is likely a lot better than the quest's hardware

kind wolf
#

i think its the settings maybe, but i dont know its my first project

golden ermine
#

this is what my campfire looks like and bigger collider is set to trigger and smaller isnt but for some reason i have to touch the smaller one to make campfire not the big one

#

you see here im inside of collider and im pressing e but wont do it

kind wolf
kind wolf
#

yes but

#

how do you get experience

#

by doing it

stable jackal
#

is there a tutorial out there somewhere that encapsulates how to preserve data ( like amount of ammo and hp left from level1) into another level?

kind wolf
#

and if you tell me that i shouldnt do it because i dont have experience you are a little funny man

lost marsh
modest dust
north kiln
#

I don't think this requires explanation

stable jackal
lost marsh
golden ermine
#

can someone help with that

sour fulcrum
modest dust
#

Is you want to spawn a new player on each level change then either just use a temp save file or make a script only used as a data container and preserve a singleton of that

stable jackal
#

i have a fps shooter dude that needs to move to an end area to get to the next level, and i have to preserve the hp and ammo remaining each time, the player is a prefab and i guess i gotta make it consistent as he goes thru each level with one clip of ammo

rotund garnet
golden ermine
#

this script is on campfire object

rotund garnet
#

looks like it should work. try checking if the values change as expected, by putting them in a Debug.Log()

#

first figure out if it enters the collision, and then if isEpressed, and then the last if statement

lost marsh
golden ermine
#

everrthing works in IgniteStartHealing();

#

see here

#

its inside collider and E is pressed but nothing happens, it only works sometimes like when I touch the smaller collider but that collider is not set on trigger

rotund garnet
#

hmm, then look for the script that makes the e-key turn isEpressed = true

#

that must be where the issue it

golden ermine
#

this is code @rotund garnet

#

where u see when i click e

stable jackal
#

if im gonna do a dontdestroyonload do i put it at the counter of the ammo and hp or on the player (who has these values)

modest dust
stable jackal
#

i see thank youu

rotund garnet
modest dust
# stable jackal i see thank youu

Unless ammo and health are for some reason references to some other gameobjects (?) scripts, then these won't be preserved. If these are normal fields on the player script / child of player then all is fine

stable jackal
#

ah crap

#

yeah they are, they're displaying things on the UI

lost marsh
stable jackal
#

what would be a better way to implement dontdestroyonload

modest dust
stable jackal
#

alr alr ill try thank youu

modest dust
#

Or a script acting as a container for this data, whatever suits you

#

could be created just before a scene change and initialized with current data

#

on scene changed use this data to initialized newly spawned GOs and then delete it

#

basically a temp save file but as a GO

#

whatever suits you best

#

(or a scriptable object)

#

(but I'm not sure about that one)

stable jackal
#

hm ill try with my limited knowledge

#

thanks lots

golden ermine
#

@rotund garnet you see here it worked but when i was slightly on the left or anywhere else it didnt work, idk why cause i was every time inside collider...its buggy idk why is that

rotund garnet
#

im not sure why that doesent work then. how does the colliders look?

kind wolf
#

In a tutorial it said to turn shaders off, but it isnt the same for me as in the video

golden ermine
#

player collider and campfire collider here @rotund garnet

rotund garnet
#

is your player collider box set as "is Trigger" ?

golden ermine
#

no

rotund garnet
#

try that

golden ermine
#

i set it to trigger and as you can see both are touching and im pressing e but still nothing

rotund garnet
#

should the orange on player outline not collide with the campfire outline?

golden ermine
#

i want player to be able to set campfire the moment he is inside campfire trigger and thats bigger box collider thats set to trigger

rotund garnet
#

hmm i cant tell what your problem is then. try to make sure that the desired collider is on the correct object

kind wolf
#

I cant find Pixel Light count?

#

or Anti Aliasing

inland socket
#

is there any definite way to stop objects from getting inside colliders, or pushing them out when they do? Making a game with magnets and they keep trying to go through walls when attracted

#

i'm moving the objects with addforce

teal viper
inland socket
#

that worked, thanks

#

the objects can also be pushed into walls with a little struggle, is there no way to prevent that?

teal viper
#

Games are a simulation of reality, which breaks at certain extremes. You either consume more procesing resources to make it more precise or avoid these extreme cases.

inland socket
#

ah alright

#

thank you

fossil hearth
#

I have a list of objects referenced by interface List<IUnit>, and it might happen that unit will be destroyed and elements in that list will be incorrect, so i try to do before operations: "list.RemoveAll(Unit => Unit == null)" but it does not work, inspector shows me thst object is "null"

#

how should I remove it

#

how should predicate look?

short hazel
#

I think it's because of the interface type. It tried to do equality on IUnit which bypasses Unity's override of == for Objects

#

You may need to do something like ((Object)unit) == null.

#

Or declare some IsDestroyed() method in the interface, which checks if gameObject == null or this == null in all the classes that implement this interface. Not sure if that would even work though, Unity object lifetime is weird

swift crag
#

yes

#

when a unity object is destroyed, references to the object don't become null

#

that would be weird magic

ashen ferry
#

what does ((Object)unit) == null accomplish?

swift crag
#

it casts your IUnit into a UnityEngine.Object

gaunt ice
#

but once the object becomes null wouldnt call isdestroyed get NRE?

swift crag
#

UnityEngine.Object is the parent type for all unity objects: GameObject, MonoBehaviour, ScriptableObject, etc.

#

It's the type that defines the special behavior when comparing with null

ashen ferry
#

aa cool

short hazel
#

And it's the one that has the override of ==

swift crag
#

Once the object is casted to that type, the operator can be used

#

or did it override Equals? i forget if you can overload ==

#

potayto potahto

swift crag
#

the only reason you get an exception when you try to use a destroyed object is because you tried to use a Unity method/property

#

and Unity throws an exception if you do that

#

Destruction is not magic. The C# object still exists.

#

It took me some time to realize that. Unity certainly makes it look like it's magic

solar heron
#

Hey how do I make my entire game lock to screen size, for example if the screen is smaller theres unused parts: heres an example

#

I have had this issue multiple times leading me to quit several projects, i dont know what to google to fix this.

short hazel
#

UI anchoring using the Rect Transform

solar heron
short hazel
#

It tells the objects what sides of the screen they are bound to

#

You can't? In runtime at least

calm osprey
#

anyone knows why every time i try to open a script it gives me this window

short hazel
#

In the Editor it's the dropdown named "Free Aspect" up there

solar heron
#

oh tysm it helps

short hazel
#

But you should make your UI adaptive to the screen size. Changing the aspect in the Editor will not be reflected in a built executable

short hazel
bitter carbon
#

anyone know how to maek it so when a method is called it changes anothers scripts canvas to be enabled

gaunt ice
#

reference to the Canvas

bitter carbon
#

yea how though

#

im not good with referencing

#

😭😭

cerulean stirrup
#

well define your canvas first

#

public Canvas MyCanvas

#

and drag and drop the canvas in the inspector

bitter carbon
#

yea but its a script from a different canvas

#

that needs to do it

eager elm
bitter carbon
#

oh yea

#

ill have to give it dif variable name

#

as i also ahve that same line for the otehr one

#

but if it works then ty

bitter carbon
#

is it cuz tthey are from different scenes?

#

@eager elm

eager elm
#

yes

bitter carbon
#

how can i fix that?

#

or is it not possible?

eager elm
#

do you have two scenes open at the same time?

bitter carbon
#

no

swift crag
#

Show what you're doing.

#

We can't see your screen.

bitter carbon
swift crag
#

you have two scenes open at the same time

bitter carbon
#

i need the canvas from the other scene in the G cnavas box

#

doesnt work tho

swift crag
#

because you can't, yes

#

You can't do it by dragging and dropping, that is.

#

You will need another way to find the canvas when the game is running.

swift crag
#

one option would be to make them singletons

#

something like this

#
public class GameCanvasSingleton {
  public static Canvas gameCanvas;
  public Canvas theCanvas;
  void Awake() {
    gameCanvas = theCanvas;
  }
}
#

You would attach this to the game canvas

#

When it wakes up, it stores the canvas into a static field

#

Anyone can now access it at GameCanvasSingleton.gameCanvas

bitter carbon
#

dont really get that and i dotn wanna just copy and paste stuff in so ill find another way thansk tho

eager elm
#

I never had to have two scenes open at the same time, are you sure it's necessary?

ashen ferry
#

I didnt even knew thats possible how do u end up with two in edit mode kekW

bitter carbon
#

idk how to NOT have that

swift crag
#

Why does the main menu scene need to reference things in the game scene?

bitter carbon
#

because

#

when the person click play

#

the menu scene script needs to disable itself and enable the otehr one

swift crag
#

but you can just load the game scene

#

the main menu scene unloads

#

it's gone

bitter carbon
#

oh ok ill try that

#

what that wontr work

#

as the onplaypressed function is on the menu scene woops i mean method not function

swift crag
#

what?

#

you push the play button

#

the play button calls a method

#

that method runs SceneManager.LoadScene("Game");

bitter carbon
#

oh ok

#

i havent used that way yet

swift crag
#

using additive scene loading and trying to do cross-scene references sounds a lot more fiddly than just loaded the game scene

bitter carbon
#

yea im new and i sometimes just do it liek the less efficient way

swift crag
#

this is why you should be following some tutorials, so that you learn the normal way to do things..

#

instead of getting stuck on weird patterns

quiet dune
#

Greetings, first time here and new to Unity/C#. Please let me know, if I'm in the wrong channel.
Can anyone help me with the following?
I'm using Resources.Load("X") as GameObject, but would like to load it not as GameObject, but as the type the prefab actually is, though the type is not known to the script, yet. Any way to resolve that?

swift crag
#

You could make the method generic.

#

For example...

#
public T Gimme<T>(string name) where T : UnityEngine.Object {
  return Resources.Load<T>(name);
}
teal viper
# bitter carbon

It looks like loading 2 scenes at the same time in the editor. It's not possible in the build, so the two scenes wouldn't be loaded at the same time like that.

swift crag
teal viper
#

Unless you're loading them additively, which you shouldn't really.

swift crag
#

ah :p

teal viper
#

Especially in their case.

#

I've been helping them in unity talk channel for a while, so I'm sure they're just misunderstanding the workflow with the scenes.

swift crag
swift crag
#

i.e. SceneManager.LoadScene("Game");

bitter carbon
#

so is awake when the scene is opened or the game

swift crag
#

neither

#

Awake runs immediately when an object is instantiated.

bitter carbon
#

ah

swift crag
#

It is true that it runs on scene load for objects that are already in the scene, I suppose.

quiet dune
#

@Fen Thanks, but the "Image" in your example is not known. That seems to be my problem

teal viper
swift crag
quiet dune
#

Its a Prefab in the Assets folder

bitter carbon
quiet dune
swift crag
teal viper
swift crag
#

Explain what you're trying to accomplish

#

Not "load a resource with a type"

#

What are you trying to make your game do?

quiet dune
teal viper
#

There's some basic level of effort that you need to put into your project.

swift crag
quiet dune
#

Basicaly I just want to spawn Prefabs at runtime from a C# script and be able to access the variables of a component script of that Prefab

bitter carbon
swift crag
#

Okay, so not just spawning them.

#

That's still very vague. Explain what your game is going to do.

#

I don't want to hear about your attempted solution

#

I want to hear about your original problem

quiet dune
#

I'f just been spawning for now and that worked well, now I want to access its script

teal viper
#

And you can easily find the relevant docs page by just googling:
"unity Awake" for example. It's gonna be one of the first results.

bitter carbon
quiet dune
#

@Fen Ants crawling around droping pheromones to lay trails. I chose to create a Pheromone prefab for that with a script to modify its scent

queen adder
#

Yo, not too sure if this is the right channel: is it possible to make the terrain (the ground) be affected by wind?
Something like in the photo, the snow on the ground is affected by the wind
(then again I'm not too sure this is the correct channel?)

teal viper
bitter carbon
swift crag
#

It talks about the broad ideas and what components do

#

Then consult the Scripting API when you need information about how to talk to those components in code

teal viper
bitter carbon
swift crag
#

please share your !code properly

eternal falconBOT
swift crag
#

You should use one of the paste sites linked in this bot message.

lilac crow
#

sure

swift crag
#

The manual has some really good information that I completely missed when I first learned Unity

swift crag
#

I never really followed tutorials when I picked Unity up, since I had a lot of programming experience and could intuit a lot of it

bitter carbon
#

yes but should i do the scripting bit, working with unity bit. 2d unity etc?

teal viper
# bitter carbon all categoriews?

Yes. Some more advanced or in depth stuff you can skip through, but try to at least remember some names and concepts.
"Working in unity", "UI", "Scripting" is probably a must. And since you're working on 2D, the relevant parts from "unity 2d" too.

bitter carbon
#

ok

swift crag
#

UI is one thing that I positively did NOT learn correctly

#

I only recently figured out how to...actually use Unity UI

#

instead of just trying random crap until it looked ok

lilac crow
#

Hello good day
im coding for my character running animation and got a problem with it.
i want my character double its speed when the left shift is pressed.
so i use (if) condition for it , everything is fine when i press left shift, animation will load, i can control it with WASD but my character speed wont double.
this is my code , where have i gone wrong?
https://gdl.space/viyidehace.cs

swift crag
#

hmm, it looks ok

#

although you set the speed after using it, so it'll be delayed by a frame

lilac crow
#

it wont change at all

swift crag
#

Is this the entire script?

#

It looks cut-off

#

If it isn't the whole thing, please share the entire script

lilac crow
#

so far yes.

#

i just started

#

is all of it i only cut the using statments

swift crag
#

Movement() isn't closed and using UnityEngine; isn't up top, so I know this isn't the entire script

#

You should always share the entire thing!

#

I want to see exactly what you see

#

You don't need to try to simplify or remove parts

#

(that can hide problems)

lilac crow
#

ok il fix it

swift crag
#

Also, one thing: what is the value of _speed in the inspector before the game starts?

#

is it 6?

lilac crow
lilac crow
swift crag
#

ok, good

#

I was wondering if you had set it to 12 in the inspector

#

Does the value of _speed change in the inspector when you hold shift?

#

Everything looks good to me. So we need to start doing what i'd call "sanity checks"

#

checking really basic things

lilac crow
#

yes its change

#

but its run with the same speed as walking animation

swift crag
#

an aside: float TargetAngle = Mathf.Atan2(direction.x, direction.y); is wrong

#

Atan2 takes Y, then X

#

also, direction's Y value is always zero

#

perhaps you meant to do Mathf.Atan2(vertical, horizontal) ?

#

oh, you don't use TargetAngle

#

right, that makes more sense. i was wondering how you were moving at all 😛

swift crag
#

or is it that the animation is playing at the wrong speed?

random ether
warm lichen
#

i asked this yesterday but no one responded, does anyone know how to make a list that auto generates points? its hard to describe but thats the best i can put it

lilac crow
rotund garnet
silk night
lilac crow
swift crag
#

Which one is it?

#

Is the character's change in position too slow?

#

Or is this an animation problem?

lilac crow
swift crag
#

Okay.

#

Change the running speed to something crazy, like 1200f

warm lichen
#

basically, you know how on social media you have a friends list or a followers list, kind of like this image. the "list points" are each person. does this make a bit more sense?

swift crag
#

no, that doesn't make more sense. I don't know what a "list point" is

#

are you asking how to display a bunch of items in a vertical list in a UI?