#💻┃code-beginner
1 messages · Page 316 of 1
So here's the funny thing
it prints anything other than the NextLevelObject
it hips the floor, it hits the upper ceiling
and it logs that on the console
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("NextLevelTag"))
{
Debug.Log("Player passed through a pipe, score + 1 ");
}
Debug.Log(other.name);
}
}
through other.name
It does match, but that also doesn't matter if the version is 2022.2+
perhaps it should be inside of update()?
No
Absolutely not
If by it you mean OnTriggerEnter
ok, tried that and it doesnt work either
Did you go through the troubleshooting guide I sent?
It has every possible reason for it to not work
ok lemme ask u a question
I am receiving neither a collision message
nor a trigger message
so which one of these is it?
do you have a rigidbody ?
which one are you trying to do?
You are trying to get a trigger message
both
🤔 what? lol
Your code says trigger
oh okay, maybe i should use that
which one are you trying to debug at this moment
It is OnTriggerEnter
No stop!
Stop just randomly trying things
collision
Go through the guide already
it doesn't matter which one u want to use.. just click the message about your error
No!
You are going for OnTriggerEnter
That is the code you wrote
So trigger message
^ if ur using OnTriggerEnter then click ~I am not getting a Trigger message~
So mine is this guy right here, right?
It's Green
so that means it should be able to work I guess right?
No, the one right above that
Your trigger doesn't have a rigidbody, only the player
ur Trigger isn't moving around w/ physics.. ^
There are multiple pages past that one, just to be clear
ok so after turning its renderer on i can see that its always following the pipes, I turned off its gravity and gravity scale so that it doesnt fall off, and the second debug outside the if statement works, the if statement never gets executed
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("NextLevelTag"))
{
Debug.Log("Player passed through a pipe, score + 1 ");
}
Debug.Log(other.name);
}
And I gave it a rigidbody like you said
No one said give it a rigidbody
rigidbody 2D
Correct, I did say that
Note that it DOES NOT MEAN "give it a rigidbody"
You have a static trigger. Which is green in that chart
what is a static trigger?
A trigger that does not have a rigidbody
yes, an object w/ a rigidbody and a collider will trigger when entering a collider w/o a rigidbody (when its marked isTrigger)
whenever I try to touch the huge fat round finishing line after the pipes
the pipes themselves disapear
so maybe before i even get the chance to touch it
Yes, so go to the next page
it automaticalyl destroys itself, and thats where it begins instantiating a new clone pipe
ok
I didn't put my MessageFunction inside of Update() (?)
I tried that and it didnt work
and you told me not to do that, so I didn't
Mine are all turned on here
That screenshot is literally telling you not to do that
See the red dot?
ok
Just do the guide and come back after
what does this mean?
mine are all enabled
so thats good right?
Imma try that and see if it works
That doesn't seem to change anything actually
btw, how do I turn this on?
I don't see any Simulated setting
yea, its the default setting
It's hinting me to report this issue to unity's developers team?
By the way, I just realized after reading this that my Player had a CircleCollider on
that page is run by one of the moderators here. (not actually unity) .. but theres nothing wrong with it
i think ur just missing something
and the Is Trigger wasn't turned on
and I turned that on just now
and it still doesnt work
lol
Are you deleting the pipes?
It looks like you delete them when going between the visible ones
yeah thats what i also noticed
Yeah, so that is the issue
You have some code destroying it BEFORE you evek get to it
but now they just disapear after i hit them or right before i hit them
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Xml;
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;
using static UnityEngine.RuleTile.TilingRuleOutput;
using UnityRandom = UnityEngine.Random;
public class Creator_Destroyer : MonoBehaviour
{
public GameObject whatIstoBeDestroyed;
private GameObject m_clone;
//public TMP_Text scoreText;
public float DestroyWhenReachesThisXPosition = -15f;
// Start is called before the first frame update
public float _timer = 0; //we need a time slowdown to slow the speed of generating new obstacles in our game
public float when_timer_should_stop = 2f;
Vector3 pipeSpawnVector;
private float speed;
private void Start()
{
cloneInstantiator();
Vector3 pipeSpawnVector = new Vector3(7.73f, UnityRandom.Range(-3.15f, 3.3f), 0);
}
private void Update()
{
Check();
_timer += Time.deltaTime;
speed = _timer * 2.1f ;
m_clone.transform.Translate(Vector2.left * Time.deltaTime * speed);
}
private void Check()
{
if (_timer >= when_timer_should_stop)
{
_timer = 0; //reset
Destroy(m_clone);
cloneInstantiator();
}
}
void cloneInstantiator()
{
float randomY = UnityRandom.Range(-3.15f, 3.3f);
m_clone = Instantiate(whatIstoBeDestroyed, new Vector3(7.73f, randomY, 0), transform.rotation);
}
/*
void Check_If_Player_Passed()
{
float localXPosition = m_clone.transform.localPosition.x;
if (localXPosition < -20)
{
float.Parse(text_score) += 1;
}
}
*/
}
I didnt change anything in this code
the only thing that I changed is the new next_level script
I also store this script in an empty gameobject
because why not
Destroy call right there....
destroy call where?
In Check()
I know
That is the problem
You are destroying the pipes
Thus you cannot collide with them
well they are supposed to be destroyed after a while, after they're no longer visible
by the way, now it seems to work
but there is a problem
it only works and debugs on the first one
that i hit
the first time that i hit it
then all the others fail to execute the if (statement)
also... after i go through one of these pipes
somehow time seems to slowdown
or the speed with which they move on the left
Hey, I'm trying to set a point light in a 2D platformer, but the light does not appear and instead increases gravity for the Rigitbody2D of the player sprite
using System;
public class playermovement : MonoBehaviour
{
[SerializeField] private float speed;
private Rigidbody2D body;
private BoxCollider2D collision;
private bool grounded;
private void Awake()
{
//Grabs references for rigidbody and animator from game object.
body = GetComponent<Rigidbody2D>();
collision = GetComponent<BoxCollider2D>();
}
private void Jump()
{
body.velocity = new Vector2(body.velocity.x, 1600*Time.deltaTime);
grounded = false;
Debug.Log("jump");
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
grounded = true;
}
private void Update()
{
float horizontalInput = Input.GetAxis("Horizontal");
body.velocity = new Vector2(horizontalInput * speed*Time.deltaTime, body.velocity.y);
//Flip player when facing left/right.
if (horizontalInput > 0.01f)
transform.localScale = Vector3.one;
else if (horizontalInput < -0.01f)
transform.localScale = new Vector3(-1, 1, 1);
if (Input.GetKey("up") && grounded)
Jump();
Debug.Log(grounded);
body.SetRotation(0);
}
}
where be thy light
no seeing anything would would affect a rigidbodies gravity
click the checkmark and on the directional light to keep it inactive and try it again
and this light isnt parented to anything right
nop
Any idea whats happening here?
the idea is that two unrelated components are affecting each other and Ive no clue why if that's the case
imma go out on a whim and say that the light is somehow creating a large dip in your fps which creates the illusion of gravity because the framerate is tanked
lel
the jump speed is multiplied by Time.deltaTime tho
and also the fps is fine
I think first you should consider fixing some of your controller logic such that rigidbody operations should be done in fixed update
input should be in update
huh ok
refer to the docs
as for your sprite, you do not need to change the localscale but instead use flipx on the sprite render's class
mk so I used fixedupdate and now the speed and jump is insanely fast
also the light still fails to appear
yep the gravity's still bugged
changing the rigidbody variable also doesn't do anything
could it be a unity engine bug?
is your code looking like the docs yet
https://docs.unity3d.com/ScriptReference/Rigidbody2D-velocity.html
Here's 2D velocity as I linked the 3D but similar idea
problem with the 2D docs is they do it in update, but really you should be doing it in fixed. Not exactly sure why but that goes against what the developers say on the forums
ok so should I put the up key detection in update
and then put the movement stuff in fixed
anything that uses rigidbody is usually done in fixed
but yeah, best practice is input in update and anything that uses physics system (rigidbodies) do it in fixed
wait whats the input code for the up arrow key
so like what should I put in the
input.getkeydown thingy
you can do by string or keycode
ok
so uhhh I put the jump key into update and know the jump key works 50% of the time and doesnt the other 50%
istg why do I always get the strangest coding issues in existence
usually you use forces for jumps and stuff, but otherwise you need to kinda flip the bool on and off everytime you jump
private void Jump()
{
body.velocity = new Vector2(body.velocity.x, 1600*Time.deltaTime);
grounded = false;
Debug.Log("jump");
}
Not even sure how this code was working before
well, beyond the freakishly large value, you're also multiplying by frame time but the method already does it for you
oh
mk then i'll remove the time.deltatime
ok so thye physics issue is gone but I still have 2 other bugs
your horizontal movement too is being multiplied by deltatime
I got that]
1.At the start of the game, the sprite appears at like 1/2 normal size. pressing the arrow keys to move solvwes this issue but its strange
2.light is gone
rip
dont change your sprite scale by localscale
SpriteRender has swapx method to do that for you
as for the light im not too sure as I don't really know too much about 2D lights
can always try remaking it and making sure it works in the scene
ok then thanks for the help
could be camera related too
yeah
https://docs.unity3d.com/ScriptReference/SpriteRenderer-flipX.html for sprite flipping
mk
// Start is called before the first frame update
void Start()``` can anyone help me? The error says that token void is invalid as well as an error saying this error was expected. does anyone know whats going on?
This is your entire code?
well these are the lines that are supposedly making these errors
if you want me to send the entire code, I will.
What is public UnityEvent on Interaction supposed to be doing for one thing
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class ObjectInteraction : MonoBehaviour
{
Outline outline;
public string message;
public UnityEvent on Interaction
// Start is called before the first frame update
void Start()
{
outline = GetComponent<Outline>();
DisabledOutline();
}
public void Interact()
{
onInteraction.Invoke();
}
public void DisabledOutline()
{
outline.enabled = false;
}
public void EnableOutLine()
{
outline.enabled = true;
}
}
``` this is my whole entire code
What is on supposed to be in your code and what is Interaction?
Where did you get the idea that that's what it's supposed to do?
Did you write this code yourself? Or are you following a tutorial?
I'm following a tutorial
Then go and double check that line in the tutorial
It's supposed to be an interaction system
Can you try to explain why I have this error? I have a screenshot
Show the tutorial you're following that gave you that line.
The error is telling you that that line is missing a ; though.
The cause is very clear. You have invalid syntax in your code. Go and compare that script to the one in the tutorial.
if errors are not underlined !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
In this tutorial we'll learn how to make an interaction system for first person games!
LINKS
Starter Project:
https://github.com/tdawsondev/FirstPersonInteractionTutorial
Outline asset:
https://assetstore.unity.com/packages/tools/particles-effects/quick-outline-115488
Simple Items Pack:
https://assetstore.unity.com/packages/3d/props/low-po...
How 2 fix size of button?
Configure it's anchors correctly. I recommend going through some tutorials on canvas ui on unity !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Would anybody know why this code isn't creating a json file?
(I assume it would create a file if the specified path didn't yet exist)
Check the project directory? It sounds like you are not specifying directory for the path
how would I specify the directory?
There's also streamingAssetsPath and persistentDataPath, see which one suits your needs
I changed the code to the below to specify a relative path but it's still not creating...
I also tried specifying an absolute path like C:/User/... but that didn't work either
No errors? Could be a permission issue
Consider logging the actual path being saved
Maybe look into Application.dataPath
https://docs.unity3d.com/ScriptReference/Application-dataPath.html
It is the path to the Data folder in the build and to the Assets folder in engine
Works for my case but not sure what you usecase is
Or check for the directory with this https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.exists?view=net-8.0
It should be created on write but still
Actually, where do you expect this to be saved @wary sigil?
You specify a relative path so it will be saved wherever your executable of the game is
I expected it to be saved in the assets folder
like an absolute path?
Unity has this for writing data somewhere where absolutely no permission is required https://docs.unity3d.com/ScriptReference/Application-dataPath.html
Use this, in combination with Path.JoinPath.Combine, to a proper file
Path.Combine is what im using
Is there a difference?
That's what I mean, yes
ah okok
Path.Join is the same but more performant and simple
Application.dataPath has been linked 3 times already lol
Make sure check your game object, changing default value will not change the value that is already serialized
xD
I used Application.dataPath, and I know I am getting the correct path from the logs, but the file still isn't created
What is logged?
Oh I just noticed I linked the wrong docs because the previous guy also did
If you are saving data you want to use this https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html
Try this instead, it points to the folder I was talking about
@wary sigil
And in this case it goes to C:\Users\<user>\AppData\LocalLow\<company name> as docs specified
So i was watching this tutorial
then I noticed .OnFootActions
wtf is OnFootActions?
It doesn't even exist as a build-in method on unity or c#
it does indeed go to this; however, the .json file still isn't in my assets folder
Because it's not saved there, read the path
Why would you want to save in assets? You are storing persisting data
Surely your tutorial would explain this or something?
The first video in a series where we are creating a First Person game!
In this video we look at setting up our characters movement.
I've setup a Discord!!! and I would love to have you help me start up a friendly community where we can all help each other grow as game developers!
Discord invite link:
https://discord.gg/xgKpxhEyzZ
Can't wait t...
nope
he just goes ahead and codes this without explaining
all I know is this
I went to the path in my file explorer and it is empty as well
Just 10 seconds in and he explained that it is a generated file you created
he never created a file called that
its the OnFoot action map he creates
Its autogenerated
Generate c# class
It's literally mentioned where you timestamped the video
And that's because you are not specifying the file, check the path
6:20 in the video
You specify just the directory
oh you are right thanks let me try that
string json = JsonUtility.ToJson(myGameData);
string path = Path.Combine(Application.persistentDataPath, "gameData.json");
File.WriteAllText(path, json);
in what way did he explain it?
cause I fail to understand
what that is
pls someone explain
i keep watching and i dont get it
I never used the new input system but my guess is that you specify the keybinds and then generate a file that listens for these
But perhaps share the generated file in here
I personally think you should create a basic input system yourself first where you manually listen for keybinds, rather than doing this
This is far more complex
you can then autogenerate a c# file from all the things you set here
yes
yep
autogenerate?
The file that is created in the same folder
from the ActionMaps / Actions you set in this window
This is mine for the above example, I dont have much setup yet cause I was just testing the functionality but it all works
I did this and it still doesn't work
Hello everyone. I have a problem where I update a mesh materials at runtime but somewhere in my code, those new materials get destroyed. Is there a way in Unity to find out which part of my code destroy the materials?
So what does it log now?
public class InputManager : MonoBehaviour
{
private void OnEnable()
{
_inputs.InGame.Enable();
}
private void OnDisable()
{
_inputs.InGame.Disable();
}
private Inputs _inputs;
public static InputManager Instance;
private void Awake()
{
Instance = this;
_inputs = new Inputs();
_inputs.InGame.Esc.performed += ctx => Escape();
}
private void Escape()
{
UiManager.Instance.ToggleEscapeMenu();
}
}
then I can use those Inputs like this
And also, log what jsonData is
My guess is that it's not serialized
Because JsonUtility is crap and you should get rid of it
yeah I never did anything with Json in unity its just the first thing that came up in my googling
why is jsonutility crap? ive never noticed an issue
logs this
It doesn't work with the majority of data objects and is extremely limited in general
Rather than changing everything in your data to support serialization, just download Newtonsoft and use something that does work properly
And what if you log the json?
oh, fair. my uses dont extend much past a handfull of floats and vectors
Yes, that works fine, although you're forced to use fields rather than properties
But beyond that it's very quick to break
how do u log the json? I'm not sure how to do that
Log the content you would write to the file just like you did with the path
It's a string too
I don't remember the full behavior for File.WriteAllx but perhaps it doesn't write the file due to the content being empty anyway
OK to answer my own question, I didn't find any way but I finally could pinpoint my problem. This is a really WEIRD behavior by Unity. Basically, I was putting my material in cache at runtime with a unique md5 key. This cache was a simple dictionary with md5 as key and the material itself as value. I never initialized the cache dictionary to = new() on the start of the project. Instead, I just put = new() in the general declaration of the property. The weird part now is that when I was usign a ContainsKey on this dictionary on first play, the result was empty and it did create my material. But then, if I stopped the play and restart right away, expecting the cache dictionary to be empty, it was not. A ContainsKey returned true but the material did not exist thus loading the purple HDRP missing material stuff.
do I need to attach specific things to the gameobjects that I want to be stored?
If nothing is logged then the code does not execute
And that is a different problem altogether
By simply adding the cache = new() in the start, i made sure the dictionary was always empty. I was assuming Unity was resetting stuff by itself but it appears not? Really weird bug...
would u know how to fix it
No because you only shared the method and I don't know how you call it
But perhaps put a debug log at the start of it and validate it's truly not called
Because you logged the path and this was logged correctly, no?
yes
So it is called
yeah but only the start() function is called
So OnMouseDown is not called?
So this whole time it wasn't as much an issue with where you saved the file, it was the fact that the whole method was not called

Next time please make sure your method is actually called
Please actually place down a log message at the start of the method and see if this is called
onMouseDown is supposed to be called when mouse is clicked right
I did enable the trigger for all 3 GameObjects which I wanted to be clicked and they are Box Colliders
Are you trying to click actual gameobjects in the world or is this some UI you are clicking?
what does actual gameobjects mean
I made 3 rectangular prisms that I want to click pretty much
Is there a reason I'm getting this error? I just want to have the transform face the direction of the velocity.
Look rotation viewing vector is zero
{
if (IsObstructed(transform.position, velocity, _radius, _mask))
{
return;
}
transform.position += velocity * (speed * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(velocity);
}```
part of UI
Delving deeper into the actual issue
Any reason why you don't just use this then? https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.IPointerClickHandler.html
Hi, I have a problem. I have created an empty object, in which I have placed an object "obstacle". I have a script that lowers the transparency of the walls if the ray between the camera and the player collides with the wall(marked by obstacle layer). I have the script for the camera and walls written correctly. However, this script doesn't work when attached to a parent object when the walls themselves are its children.
What is the best way to handle this situation? At the moment, as a dumb beginner, I add the script to each child object manually.
P.S Notify me if my question is related to another branch
thx
Hello! Im trying to work with scriptable objects for the first time and Ive ran into an issue
https://gdl.space/esovuyaqes.cs
here is my SO and my method that writes data into it. The lines outside of the for cycle (for creating entirely new entries) works just fine and the debug logs at the bottom show correct values. However, the part that adds new set of distances into an already existing entry throws a null reference error on line 25, which Im not sure I understand why. I assume the list is not instantialized, but that makes no sense since Ive added something to it before...?
share the script please
why do you ask for coding help without sharing the code, what's the point
Mornign i have this function ``` public Transform GetEnemyAtOriginalPos2()
{
for (int i = 0; i < cubes.Length; i++)
{
if (cubes[i].position == originalPositions[1] && cubes[i].childCount > 0)
{
return cubes[i].GetChild(0);
}
}
return null;
}``` that checks what enemy is at postion 2. then in update i have ``` if (GetEnemyAtOriginalPos2().GetComponent<BattleCharacters>())
{
currentEnemy = GetEnemyAtOriginalPos2().GetComponent<BattleCharacters>();
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
if (GetEnemyAtOriginalPos2().GetComponent<BattleCharacters>()) i thought this would stop that
this doesn't work for me either...
do I need to add an event trigger to the gameobjects?
debug the code
either GetEnemyAtOriginalPos2() or GetComponent<BattleCharacters>() is null
You need the EventSystem too, is that in the hierarchy?
Also, you are trying to click an UI object. Is this a button? Because then you might aswell use a proper button
that is correct it is null thats why i wrapped it in a if yet it still throws null
chat gpt code?
not a button but an object
I also added eventsystem to a separate button and I don't think it will allow me to add another one
which one is null
not without its help 
It should not be in a button, it should be in the root hierarchy
The object that must be clicked must have that interface in a script as a component
you need to do
var enemy = GetEnemyAtOriginalPos2();
if (enemy && enemy.TryGetComponent(out BattleCharacters battleCharacter))
{
}
@honest haven
If you did all that, log a message in the method to call and see if it's called
someone correct me if Im wrong lines 41 and 51 are the main issue - you arent actually fading it gradually, just setting it to a set value
bacause i have alright with my code. I just want to know how to make work parent's script for all children objects and don't attach script for all children objects mannually
ask chat gpt like you already did
what should I have in the event trigger for each gameobject?
I don't have the right decission
Event trigger?
for what?
for clicking on a gameobject
I don't recall that component, you should just have a script with IPointerClickHandler
Or a button
you can use it just fine
And the event system should be in the root hierarchy
that looks like you have dragged in a script rather than a gameobject containing that script
add whatever youw ant to PointerClick method
the EventTrigger components implements it already
can be used without code
Ah good to know, then you can use that instead
im not sure what will happen tho if use EventTrigger + your own interface implementation
on the same game object
ok I removed event trigger but I have this script but it isn't logging anything when I click
do you have a physicsraycaster on your camera?
im not doing it on a physical object but on a gameobject i created
What the term called for using code to make a characters bone face a certain way? I want to make the spine face toward the mouse
the gameobject has a collider?
box collider
then it is a physical object
oh interesting
you really should read the documentation
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/EventSystems.IPointerClickHandler.html
inverse kinematics
Maybe "1-bone IK" or "look IK"
thanks
May I film here my problem ?
@abstract finch Is it a 3D character?
Either way @wary sigil the issue you mentioned is now boiling down to two separate issues. Always make sure you actually ask help with the problem rather than one of the reactions that might happen from it, or you are prone to the XY problem: https://xyproblem.info/
yes im doing a isometric/topdown atm
If yes, you can try something like spine.rotation = Quaternion.FromToRotation(spine.up, dirFromSpineToMouse) * spine.rotation;
Might be something else than spine.up depending on your bone orientation
https://docs.unity3d.com/Manual/InverseKinematics.html
I'm using this
But yeah you can do it with IK too
will this override the Animator component?
i remmeber having to do something to make it override animator
If you do it in LateUpdate, it will apply after animations
ahhh thanks
just do it with IK
I have continued going down this rabbit hole and I have found out that when I stop the playmode and launch it again, the list of distances isnt instantiated anymore, but the list of patterns is. What is the reason and how do I solve this?
I reread through documentation and I guess I was just connfused on what is a UI object and what is not 😭
but I added a physics raytracer to the main camera but the logs still don't work (things aren't logging when I click on top of items)
and to add to this - when I open the SO in a notepad, nothing is actually getting written into it despite me seeing some entried in inspector
anyone has a tutorial project that i could learn about bubble shooter or puzle boble game in 2d?
thats very specific, have you tried googling for it? Maybe just try starting and then ask if you have a specific issue
ive tried, its for my college exam
but usually its paid project or source code material
funnily enough i was planning to make one
well just to let you know, you most definitely arent gonna find a tutorial that teaches good coding practices while making a full game. They are going to be complete shit, but hardcoded enough that everything works and cant be extended further.
Its really best if you start, and just split up what you need to do in steps. ask if you have specific questions
but the whole series wont be done for another month
@wild mantle how much programming do you already know?
okeyy then
much, i would say intermiediate. I just need like a scratch pictures on how the game works for logic, then i wil build it with my own version
hello, i want to use a int[,,] map variable in different scripts but everytime i "import" it in another script the variable is null. i'm blocked
how can i do it ?
i tried to use public int[,,] map; in every script but it doesnt work
you just declare it, where you create the array?
- It's a 3d array, not a map.
- it follows the same rules as any other class member. If you want to access it from outside, you do it via a reference to the instance that holds it.
i create the array here
Share the errors and code that throws them then
there isnt any error, i just cant get the array in another script, it gives me a null object
That sounds like an error to me
it is an error
what do you mean by an "error" ?
how you reference the WorldGeneration
Error message in unity console, what else?
public WorldGeneration worldGen;
there is nothing that appears in my unity console
Then how do you know that it's null?
because i wrote if map == null to test it
again, it is just a declaration, show the inspector/ the place that you assign it
Then share that code...
Probably. We don't have enough info.
i'm making a player controller and i need to get when the player press E (use key) using Input.GetKeyDown(KeyCode.E) but for some réson its returning true 1/10 of the time
yes
the update rate of input=rate of calling update not match with the rate of fixed update
so capturing any key down/up event in fixed update not work
I have a script that gets the mouse position on the camera from a raycast in order for my character to look at the mouse position, however I simply want the character to look in that direction rather than at the hit point. How would I be able to do that? The surface is flat.
if (success)
{
// Calculate the direction
var hitPoint = position - transform.position;
hitPoint.y = _minYLook;
_mousePos = hitPoint;
}```
Do you mean like... The player looks at whereever the ray hit 0 on the y axis?
In my game the player's gameobject is destroyed when they lose, when I restart the game (reload the scene) I get nullreferenceexception (The object of type 'GameObject' has been destroyed but you are still trying to access it.) from that object even though it is set up on void start(), I believe the problem to be the scene not truly resetting and maybe some variables carrying over? I am not really well versed in the structure on how scripts in unity operate which could be my issue.
Did you do this?
Tbh you should try and find out what is null first
But if you configured your settings like that then I probably know why
its turned off
do variables in unity reset when a scene is reloaded?
Mostly yes
If you disable reload domain&reload scene tho, it won't refresh static variables
that probably why
Reloading the scene (not exiting and entering play mode) can expose errors.
can anybody help me please? I'm coding and I'm stuck for a while on one thing
So you did enable play mode options and keep the others off?
I didnt enable it
I never touched it
I think i found a guide for what i need basically the ray direction rather than the point
Ah, yeah, if you don't restart the game when reloading stuff it will throw a lot of errors indeed
now I turned it on and I still got the same issue
When you said "Reload the scene" do you mean exit and enter playmode?
Using Scenemanager
I meant just reloading a scene. You might have issues you aren't aware of until you start doing it.
when I exit and enter I get no errors
Not completely familiar with what scene manager does buuuut normally it shouldn't cause issues... Right?
The Gameobject is inside of a static list so maybe thats why?
do static lists get reset when you reload a scene?
I don't think they do tbh
Why would they
Is why to be safe I do a lot of initialization in Awake()
Static things aren't part of any instance in the scene, so they don't until you restart the app (or exit and enter play mode)
Ok I see
if (movementController.moveInput.x != 0f)
{
Quaternion targetRotation = Quaternion.Euler(cameraHolder.localEulerAngles + Vector3.forward * strafeTilt * movementController.moveInput.x);
cameraHolder.localRotation = Quaternion.Slerp(cameraHolder.localRotation, targetRotation, slerpAmount);
slerpAmount += Time.deltaTime;
slerpAmount = Mathf.Clamp01(slerpAmount);
}
else
{
if (slerpAmount <= 0f || slerpAmount == 1f) slerpAmount = 0f;
slerpAmount -= Time.deltaTime;
slerpAmount = Mathf.Clamp01(slerpAmount);
Quaternion targetRotation = Quaternion.Euler(cameraHolder.localEulerAngles.x, cameraHolder.localEulerAngles.y, 0f);
cameraHolder.localRotation = Quaternion.Slerp(cameraHolder.localRotation, targetRotation, slerpAmount);
}
slerpAmount starts at 0. It rotates to strafeTilt properly, but doesnt rotate back smoothly. Why?
I will try and reset the static variable on Start and see what happens I guess
Does it simply snap back to 0?
yes. But smoothly slerps to strafeTilt
So if you move, slerpAmount will increase to the limit of 1...
But then once you stop, it will find that slerpAmount is 1 and immediately set it to 0
Hello, I'm coding something and I've been stuck for a while, can anyone help me?
if (slerpAmount <= 0f || slerpAmount == 1f) slerpAmount = 0f;
Is this intended lol?
Don't ask to ask xD
Explain the issue and share relevant details instead of this. There are plenty of people that can help
yeah I'm trying to reset slerpAmount to use it again to reset the rotation
But you are also decreasing it after
If you can't read what people tell you, why would they spend the time trying? relevant details
Show your code, explain your problem.
I'm learning, and I'm programming the death of an enemy after its animation, but when I hit it, instead of doing the animation and disappearing it disappears directly, so I added a coroutine, but now it plays infinitely and doesn't disappear...
Please share all the relevant !code about your issue
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Your animation might be on loop, if you're detecting the animation's end
If you're running a routine every time it gets hit, it'll stack them. You need to disable the collider or add a bool to check isDead
I have a bool that detects if your life is empty and when it is empty that is when I try to do things
thats my bad, I mistyped but even after I replaced -= with += it didn't have an effect
Okay, just gonna explain what I think you're trying to do:
If moving:
- Increase slerpAmount to a max of 1
If not moving: - Decrease slerpAmount to a min of 0
Share the code
public class HurtBox : MonoBehaviour
{
private float animTime = 0.40f;
private Collider2D currentCollider;
private bool animationTriggered = false;
private void OnTriggerEnter2D(Collider2D other)
{
currentCollider = other;
if (!animationTriggered && other.CompareTag("Enemy"))
{
Animator enemyAnimator = other.transform.parent.GetComponentInParent<Animator>();
if (enemyAnimator != null)
{
StartCoroutine(TriggerDeathAnimation(enemyAnimator));
}
}
}
private IEnumerator TriggerDeathAnimation(Animator enemyAnimator)
{
animationTriggered = true;
enemyAnimator.SetBool("lifeIsEmpty", true);
yield return new WaitForSeconds(animTime);
currentCollider.transform.parent.gameObject.SetActive(false);
}
}
Also, are you using that slerp as a mean to lerp from current rotation to target rotation?
I'm just trying to get the camera to tilt towards the direction of movement if moving sideways
so yeah thats a good interpretation
yeah
Tbh I think that you can just make your life simple and always slerp by a fixed amount
For basic purposes it works, although there might be an issue when dealing with different Frames per seconds...
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I thought thats what I'm doing. What would be your solution?
Well... I mean that with how you're doing it you're nearly as well off just making it slerp 1% from current to target rotation everytime
Though somewhat recommended to do it at a fixed timestep
How can I display a countdown timer between two dateTimes?
IEnumerators don't count down when you're in scene mode while the game is running, just a reminder since it might cause a lot of confusion
So what can I do to make the death animation play first and then disappear?
if it's small, you can just format it, or use a paste site for large code blocks. most people can't see the script within discord (like myself) . . .
Tbh a simple solution is simply to use an animation event at the end of the death animation
I don't know how that is, my code before adding the coroutine was like this. What can I do from there?
Here, look at this, you might find it really useful
https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
thanks, I'll see
You can easily use that to make the character shoot projectiles at a certain point of an animation, or, in your case, make the character disappear
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
im trying but, It doesn't let me deactivate the enemy when recording, it only lets me change its components, not deactivate the enemy
Idea is basically that it moves x% to the target, and as it approaches target the amount it moves slows down.
Unless if you use it in fixed update or so though, otherwise it will have trouble with Time.deltaTime, you can ask me for details why if you're curious
You need to make a public method for it '^^
It's limitations often feel annoying but it's one of the easy ways to get something like this done
this doesn't work though
it just snaps
Uhm, what value did you set in slerpStep?
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
// Update is called once per frame
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(sidewaysForce * Time.deltaTime , 0, 0);
}
if (Input.GetKey("a"))
{
rb.AddForce(-sidewaysForce * Time.deltaTime , 0, 0);
}
}
}
so why is my player not automatically propelling forward?
I tried 1 and 0.2, both values just snap
im following a brackeys tutorial
xD nooooo set it to at least 0.01
DateTime endDateTime;
TimeSpan shiftTimeDiff;
private void Update()
{
endDateTime = DateTime.Parse(shiftEndTime);
shiftTimeDiff = endDateTime.Subtract(DateTime.Now);
}
are the values actually set in the inspector also? or are they just 0
yep
they're not zero
that just causes it to rotate less, its not smooth. I'm pretty sure slerpStep needs to increase in value over time, at least according to the docs
Why does this make the object move up forever? It works fine on another project.
why are you importing visual scripting and input system if your not using them
put a debug.log in the if statements to check if they even run
That's the case if you're lerping from original to target
use GetKeyDown
You know what slerp/lerp does right?
Why wouldn't it? You're setting an upwards velocity
ok nevermind, i just realized that that only seems to happen if I attach a camera follower script on to my player via my camera
that was the actual problem causing this
i removed it and he moved forward
kinda, Its just interpolation right? Slerp is spherical interpolation. I want it to smoothly rotate, then smoothly rotate to the original position if not moving
Yes
🤦♂️ your right
slerp(x, y, 0) = x
slerp(x, y, 1) = y
slerp(x, y, 0.5f) = right in between x and y
Why are you multiplying forces by deltaTime?
yes, I get that
So if you set the rotation to the center of the current rotation and target rotation, would it really not work lol
Quaternion targetRotation = Quaternion.Euler(cameraHolder.localEulerAngles + Vector3.forward * strafeTilt * movementController.moveInput.x);
cameraHolder.localRotation = Quaternion.Slerp(cameraHolder.localRotation, targetRotation, slerpProgression);
slerpProgression += Time.deltaTime;
slerpProgression = Mathf.Clamp01(slerpProgression);
I want to smoothly rotate it to strafetilt along the local z. Like this. I'm trying to get the reverse of it now
perfect, thank you very much, it works
No problem, have fun coding
🙂
if (!EventSystem.current.currentSelectedGameObject) {
is this equivalent to if (EventSystem.current.currentSelectedGameObject == null)?
Yes
thanks
if (movementController.moveInput.x != 0f)
{
Quaternion targetRotation = Quaternion.Euler(cameraHolder.localEulerAngles + Vector3.forward * strafeTilt * movementController.moveInput.x);
cameraHolder.localRotation = Quaternion.Slerp(cameraHolder.localRotation, targetRotation, slerpProgression);
slerpProgression += Time.deltaTime;
slerpProgression = Mathf.Clamp(slerpProgression, 0f, 0.99f);
}
else if (slerpProgression != 1f)
{
if (slerpProgression == 0.99f) slerpProgression = 0f;
Quaternion targetRotation = Quaternion.Euler(cameraHolder.localEulerAngles.x, cameraHolder.localEulerAngles.y, 0f);
cameraHolder.localRotation = Quaternion.Slerp(cameraHolder.localRotation, targetRotation, 1f);
slerpProgression += Time.deltaTime;
if (slerpProgression == 0.99f) slerpProgression = 0.999f;
slerpProgression = Mathf.Clamp01(slerpProgression);
}
This is what I currently have. Rotate smoothly on move, then snap back when there is no sideways input. After the if statement, It should remain in the rotated state, then I can reset slerpProgression to zero. I should then be able to smoothly slerp it back to 0 rotation along the z axis.
Um, you know... Maybe have a try calmly explaining your code's function line by line to yourself?
or at least thats how it works in my head
Like do it verbally, not in your head
Hi, can I please get some help on a project
https://www.youtube.com/watch?v=rJqP5EesxLk&list=PLGUw8UNswJEOv8c5ZcoHarbON6mIEUFBC
i'm following this tutorial, and i'm currently up to the gravity part, but i can't get it to stop applying force constantly, can someone please help me to get this part working?
The first video in a series where we are creating a First Person game!
In this video we look at setting up our characters movement.
I've setup a Discord!!! and I would love to have you help me start up a friendly community where we can all help each other grow as game developers!
Discord invite link:
https://discord.gg/xgKpxhEyzZ
Can't wait t...
Should I be using a different variable to reset the rotation?

Really... What do you want your code to do? What is supposed to happen when you turn to the opposite direction?
If you only want your character to tilt depending on your movement axis, and slow down tilting as it nears the target tilt, you've got the answer already...
would anyone be able to help?
Busy sorry '^^
And Imma be out after this one
Well tbh you're setting your y velocity to -2 whenever you're onGround
Though character controller has a slight issue, you actually need to move down a little all the time, as otherwise the character controller assumes that it's not on ground every other frame
try 2 c# if(!isGrounded) playervelocity.y += gravity * Time.deltaTime; instead of c# playervelocity.y += gravity * Time.deltaTime;
like this?
!isGrounded
read your code
playervelocity.y += gravity * Time.deltaTime;
// Use isGrounded property of CharacterController
if(controller.isGrounded && playervelocity.y < 0)
playervelocity.y = -2f;
controller.Move(playervelocity * Time.deltaTime);
It makes no sense
That's what I was talking about xD
about it
remove one of the & signs?
@pure haven, does it work in guide?
Tho really, CharacterController has a bit of an issue where if you don't move down against the ground everytime before a groundCheck, your onGround will flicker
yeah
what do you mean?
&& means true if both the right and left conditions are true
& is something totally different
alright
the code works in guid, and if you want i can send a picture of the code from the guide, it may be as simple as i've missed something because dyslecia
send
I think why they keep adding velocity down is simply cus of the issue I mentioned lol
so the character controller is constantly performing the checks, meaning that it's continually applying the force assigned to gravity?
here's mine as well for reference
32 row, try if(!isGrounded)
9 row, try private bool isGrounded = true
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
seriously? A primitive varaible can never generare a null ref exception
really? ok, wait
private void HandleInputKeyboard()
{
if (canPlay)
{
float h = Input.GetAxis("Horizontal");
forKeyboard += h /3;
Mathf.Clamp(h, leftLimit, rightLimit);
spawnPoint.transform.position = new Vector2(forKeyboard, 4);
if (Input.GetKeyDown(KeyCode.Space)) MouseUp(); // This thing doesnt override any value
}
}
I dont know why but value doesnt clamp, can someone help?
that has apparently fixed it
Well the code does this:
28~31. move by the player's input
32~33. add velocity downwards (With Ktoto's addition it has a condition of having to be on ground)
36~37. set the velocity to move down by a fixed velocity if not flying up and on ground
39. move by vertical velocity
you're right, build error only
ah wait im dumb, i clamp wrong value...
oh, wait
thank you for explaining this
No problem, hopefully it helps you understand some stuff better
thanks, I've been making the jump from python so this has helped
ok, you're right, @languid spire
I know I'm right, you should look up the difference between value types and reference types. Hint, values types can never be null
Just to let you know
Natty hasn't finished this series yet so it's a dead end ahead of your if you continue following this series.
Hi there Can some One help me with integrating Ads if they have done it before please provide the script and the method to do so i have tried unity doc's and youtube but wasn't able to do it succesfully
also i need Help with NavMesh it is not there in the designated place like with the physics and all that stuff
please do not crosspost across multiple channels. stick to one and delete from the rest please
as long as i can put together a level or two
that'll do
but on a note, in the tutorial it says mathf square root, etc, when i've typed that in on unity it gives this error
mathf Mathf
And I found that if I followed Natty's tutorial on gravity, my character would be gliding rather than falling
i had that!
It's not that nice in term of movements and logic
thanks to the people here i've got that fixed
How 2 make TMP on runtime?
His State Machine is really good
and so that the player has a little recoil when hitting, I put a variable that is the recoil force and a function that does: hero.velocity = new Vector2(bounceForce, hero.velocity.y); My player controller is an instance but when I call the function from my hurtbox, which is when I hit and deal damage, it doesn't do any recoil.
same way you make any other object. You make a prefab and instantiate it
ok, can i save it in file?
do you know what a prefab is?
yes, i can
no
Prefabs are a special type of component that allows fully configured GameObjects to be saved in the Project for reuse. These assets can then be shared between scenes, or even other projects without having to be configured again. In this tutorial, you will learn about Prefabs and how to create and use them.
ok, i already use it with Resources.Load<>()
sorry for your time, turns out another script of mine was setting the Y and Z rotation values to zero while changing the X value
🤣 Okay
I have this simple function( public void Bounce(){
hero.velocity = new Vector2(bounceForce, hero.velocity.y);
}) that is to push the player and I call it when I damage the enemy but it doesn't work.
first. !code
second. define 'doesn't work'
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I mean that despite everything the player is not pushed
I want to disable a script in a gameobject with another script. Would gameObject.GetComponent<ScriptName>().enabled = false; Work? Given scriptname is the valid name of the script attached to the game object
Hi, i'm now getting this error,
basically it's saying the look action map doesn't exist within the playerInput.cs
how would I fix this?
if ScriptName is on the same gameObject as the calling script, yes. Otherwise no
Awesome, cheers
it is exclusively affecting this line in the input manager
and I call this when I hit an enemy but it doesn't push the player
How do I pass a script as a type? because <> requires it to be a type and cant gather that type from a string representation
Is there a reason why you do this? That sounds like a very uncommon use case
Either way, make a dictionary of string keys representing the script name, and Type values for the script type
Most, if not all methods accepting a generic type, also accept a play Type type
I have an XR object that uses premade scripts and I want to disable/enable behaviour based on a settings object that loads playerprefs
Okay I have a weird but functional way of doing it
(XRComponent.GetComponent(item) as MonoBehaviour).enabled = false;``` just incase anybody needs this behaviour
item is type string, so you can just have an array of strings, ensure the strings are the class names and it should disable them accordingly
I'm still having this damned error and have no idea why it isn't working
how 2 get access 2 this component throught code?
public TextMeshPro text;```
why am i being X'd? loool
because that is wrong, it is not a TextMeshPro component
it is a TextMeshProUGUI
close enough loool
no, because TextMeshPro is the 3d mesh text, not the UI one
because gameObject.GetComponent<TextMeshPro>() = null
eh well the formatting of how its done is correct, even if the type is wrong
aaaaah. learning something new everyday
so, I can place it not in canvas?
if i assign it like this when does it runs private Player player = PlayerManager.Instance.player;
in basic c# on program start (may be before Start())
way too early. assign it in Start at the earliest
even before awake?
okay
yes
idk what is awake
A method that runs when an object is instantiated (or runtime begins, if it exists before runtime starts)
It runs one time in the objects lifetime
that means its safe to assign it like this if i get it from a singleton
no, i don't think so, but it'll be not very later
if you assign the Instance property of your singleton in Awake then do not access it until Start at the earliest. the sort of random execution order of your scripts will lead to NREs and other issues if you access it before Start
field initializers run when the object's constructor is called which is way before even Awake runs (which is also the first second unity message to be sent to the objects)
I see so if this code runs before start then it might cause probs
TMP_Text would cover both UI and 3D versions
https://hatebin.com/jwzcbuhzcb I am just trying to disable the image that is a crosshair. I drag the image in hierarchy but it stopped working now. Why is that?
Could it be that the image is inside the Dialogue Manager's prefab's canvas? Is it okay to have two canvases in scene?
what is "stopped working" mean in this context
two canvas is fine, depends what ur doing. Always check the Event System in playmode to debug your camera ray
I could disable my crosshair with crosshair.enabled = false I meant before moving them into the canvas I believe.
Interaction is working fine if thats what you mean with camera ray
Its just the crosshair image does not get disabled for some reason
You mean crosshair.enabled = false;
is the line running at all ? but debug.log inside
all right I will try
define disable? hide is not same
crosshair.enabled = false means disable no?
i mean disable the image
I put crosshair in a different panel and made the panel gameobject setactive false and its working now.
to hide the Image - better to call SetActive(false) on the gameObject... yep indeed
Is wrong approach?
ey, how did you make that you see the icons on the right?
enabled is only for a component/monobahaviour - generally I suggest SetActive on the gameObject holding the Image etc
So what I did is correct. I put the stuff I want to hide or disable in a seperate panel and just calling setactive accordingly
yes
A friend set this project up. Its some kind of extension I believe but not sure
yes its a plugin https://github.com/WooshiiDev/HierarchyDecorator
Thanks a lot.
tnx, that is so usefull
disabling an Image component should be perfectly fine
unless you were setting it back to true somewhere, there is nothing wrong with disabling component to hide img btw
yes if you have a link to the component it will work - Although there is still the canvas renderer on there so I wonder if it is an optimal way to do it
I do it all the time, it works without any issues
No like game starts with the crosshair enabled. But for some reason I could not figure out why it was not working.
I have this little teleportation fade screen and I want to disable the crosshair image.
then enable back again once player teleports
ok cool - I wonder what is fastest... if there is cost of canvas renderer left behind... etc! Well I do not need to know unless really slow
What I did in my case is way more convenient I believe. I was enabling and disabling stuff inside methods one by one. Putting them all together in a panel is better but still... Wonder why it did not work
the differences are negligible, everything was already loaded in memory
Instantiating and Destroying is what causes garbage in that sense
disabling does not, cause object is already loaded but preserved untill destroying (scene switch or manually)
Do non programmer people you worked with ever get upset about the fact that they had to drag and drop stuff in the inspector if they wanted to set up things by themselves?
noo they actually prefer it for me
they hate when i do "everything in the script"
and want all sorts of custom editors
I have some serialized stuff and I'm kind of worried that it will be a hassle for them.
Nothing hard on my side but maybe for some people that are not programmers. Though you do not have to be a programmer to drag and drop stuff haha
exactly.
A quick question. Is it okay to have empty scripts attached to gameObjects that I want access to through script? Just to FindObjectOfType and get whatever I want?
I mean you can sure, if its already in the same scene ideally stick to Serialized fields
Well I am going to be honest. I have some prefabs that got serialize fields on them. When my friends will want to work and just drag and drop the prefabs. I am afraid that they will find it overwhelming to drag stuff
just keep in mind Prefabs cannot reference scene objects
yes thats why they have to keep dragging when they want to use prefabs right?
since thy live in the project folder
if prefabs are added to scene then yeah, otherwise pass it through the spawner/instantation script that does
so make a script that adds the references that does all the dragging inside?
wdym by all the dragging?
I mean like. I have a prefab that lives in the prefab folder. I take it out and place it in the scene. Then in the inspector all the serialized fields are empty because I have to assign the relative objects.
right
Thats what I meant by dragging. Since they cannot hold references.
they can only reference other assets (prefabs, scriptable objects, sprites etc.)
(when not placed in scene)
assets that are in the folders?
Assets are files in the project. As opposed to GameObjects in the scene
yes like sprites etc
A prefab is a GameObject made into an asset
ahhh makes sense.
Assets cannot reference things in scenes, since an asset always exists, but the objects in a scene only exist when that scene is loaded
but assets can reference assets because they always exist
Yes. So your prefab can reference another prefab, or a material, or an audio clip, etc.
yeah they are living on your disk and are tangible objects
Wooh okay damn. This shit was bugging me for weeks. Thanks for the help!
How 2 get button component throught code?
make a reference to the Button component, assign it, use it
So im working on my inventory system in unity and I have a object in the scene I want to pick up and store in another gameobject variable. this variable it public so I can set the picked up object to it. So my questions is how do I then set the picked up object to the variable then be allowed to delete the picked up object with out the variable losing its value.
i have only 1 button class & this is a just some onMouseClick handler
well , if you destroy it the reference is null because the specific object is missing
& tabButton but this is from basi c#
so a custom button? Not sure what you mean
yes i know, so how would or could i do it.
Hide the object? store the object as data to recrate, many ways to do something
depends on many things
this is the only one button class tha i have
So you made your own Button class named exactly the same as Unity's
well i basically want to transfer it from a scene object into a variable, I dont want it to stay in the scene.
You shouldn't name a class the same as a Unity one, you'll need to specify which one you want every time you use one
so, i tryed 2 use this script in ui & it doesn't work
ofc it doesn't
did you lookup docs for OnMouseDown ? doesn't work on UI
its for colliders
If this is meant for a UI button to call a function when you click on it, why not just use the actual button component from Unity that lets you add a function to call on click?
yes, i even tried 2 add collider 2 ui obkect
no don't do this way
ok, now that class called Butto
ui elements should not have colliders
you outta be using the canvas itself with Raycaster already built in
Just use the unity Button component on the UI object like Digiholic said
because button is creating on runtime
So? You can still assign a function to a UI button after it's instantiated
make a prefab for the button that already has the Button component on it
spawn it in the canvas as child
how? i even can't get component, how can i assign functions on runtime for it?
What do you mean you can't get component
Your function doesn't require any external references, just change name from OnMouseDown to something else non-unity.
Like OnButtonClicked() then link that in OnClick
this mean, that GetComponent<> method needs something in <> but there's no button class as u can see at #💻┃code-beginner message
You don't even need that, just link the function in inspector
There is.
You just don't have the using or something
on the OnClick
But yeah, what nav said is better
no, i have object that use this method
that doesn't make sense
it's creating on runtime, i need 2 hire workers for linking on runtime different functions?
wdym?
Yes, and you'd but in the button class.
https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.Button.html
But you really don't even need a GetComponent, if you're spawning in a button at runtime just make your prefab of type Button and use that
If its creating the Button make it a prefab with the OnClick already linked?
You are trying to Run Open URL right? and just pass a diff url when you make button
i need 2 make all possible parameter prefabs?
when you create the button pass that info directly
no, i already use nonUI buttton for this function
MyCustomButton theButton = Instantiate(etcc.
theButton.Url = "http://something" ?
thx!
url opening method is already implemented by different way
idk man Im just going by the limited info and code you sent 🤷♂️ maybe I misunderstood it
hey there guys! testing a point and click game, i want the player to only be able to click and move within the blue object but not entirely sure how to add those boundaries
You could have a second "fake" mouse pointer gameObject
Just keep that on your mouse always, except when your mouse is outside that area, then have it on the closest point possible to your real mouse in the blue area
or something like that
use colliders
thanks for getting back! would that not make it so the mouse itself cannot move beyond the bounadaries? i want the player to be able to click outside of them, in case there are interactable objects outside etc, just not move outside
and IPointerClickHandler
Ah i though you wanted the mouse only to be moveable in the area
Hello. Is it possible to make that raycast reacts different to different? Like when it collide with 1 layer it do something, but when layer 2 it do something else.
Either two different raycasts with different layer masks, or put an if statement inside the raycast block
how?
What I said here
To check which layer you hit
How I can use that with raycast?
do you know what an if statement is?
if
(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out RaycastHit hitInfo1, 2.5f, czerwony))
Where I need to use if?
sorry new to raycasts xd
this is not a concept specific to raycasts
When you want to check if a condition is true before executing code
but how I can make that that reycast returns different value with if?
You don't. The raycast returns true if it hits something
So you check that thing for a property you want to know about
and check if it is layerX or if it is layerY
before doing the code you have this raycast run
okey thanks
Hey does anyone have any tips on learning how to code 2d movement?, im really reluctant on watching tutorials as i dont want to merely copy,
You're not meant to merely copy when you watch tutorials
you're meant to follow along and understand/learn
if you were just meant to copy there would be no need for a tutorial, you'd just download the project.
Certainly. I recommend https://dotnet.microsoft.com/en-us/learn/csharp
Ive started with unity and i have learned how to introduce tiles so next steps ahead!
Consider first watching, then implementing what you've understood
If you haven't, watch once again
You're writing the message "hello world" in the C# console when the program is started
No i mean i wrote that so i get that but the stuff above.
What stuff above are you talking about?
namespaces?
above console.writeline, as in the sativ void ect
the static void Main(string[] args) is the default method, which is executed when the console app is started
Oh so is a method like s ubroutine in python?
It's described as
the entry point of a C# application
entry point of the whole program, and you dont need it when writing c# in unity
I don't know python.
what about them?
IS that all necessary?
No, the namespaces, which are darker, are redundant
This means, currently, from all those namespaces, you only need System
It is a static function named Main that returns void, and takes in an array of strings as a parameter which it stores in a variable named args
In a standalone C# program, a method with that signature will be executed when the program runs but Unity is not a standalone C# program so that function will not do anything unless you call it from inside of Unity
You might wanna ask in the !cs server
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
how do I stop this from happening
u cutoff most important part lol
The bottom part of the image you cropped out has more details on where exactly in the code the exception occurred
Then you can ignore that
Then it probably isn't your code. Looks like an editor issue
yeah somewhere the editor visuals took a poop
If it breaks stuff, restart the editor and it'll most likely get rid of it
I'm trying to match up unity's Offset Even Q coordinate system for hexagonal tilemaps with my Cube Hex coordinate system, but I'm struggling to get the conversion right.
The debug shows the pawn coordinates in Offset from left to right:
I did what I could on paper:
here a is an integer, and I've lined up the two axes with the two rows of pawns
https://www.redblobgames.com/grids/hexagons/
I' m trying to use redblob as a guide but unity doesn't seem to line up
Yeah Unity uses its own cockamamie scheme
it's awful
they could have at least added support for the cube/axial version
I have no idea if this is helpful or valid
but I made a hex game a while ago and made these conversion functions
https://gist.github.com/jschiff/fed5a3f55e8018a84888feac20919996
It's supposed to convert between Unity Cell coordinates and Cube coordinates. Not sure if it's applicable for you.
that redblob tutorial has all you need to roll your own HexCoordinate class, can you use JUST that everywhere, to keep it consistent? you NEED the unity kind?
I was using unity tilemap for the board
yeah hex on tilemap is pain when following redblob
Unity uses the offset even q so I was hoping it'd be easier to convert
See if it works for you: #💻┃code-beginner message
I think the redblog has stuff on how to convert to that.. haven't looked but preators stuff prolly does too
yeah I' m checking praetor's code
I tried the redblob conversion but unity has everything inverted and negated and idk how to logic that out
note.. that's actually TWO-numbers (z is always 0)
Note I wrote this 3 years ago so i can't walk you through what it's doing if I wanted to.
what does (this in) in a parameter mean?
this is for an extension function
in is to pass it by reference and not allow modifications to it.
it lets you call the function like it was a member of that parameter's type.
in is basically a performance optimization.
this lets you do myCubeCoord.CubeToUnityCell() for example
instead of CubeToUnityCell(myCubeCoord)
OH!
so I can just use it on a vector3int rather than having to call an instance of a class?
that's pretty cool
yes, but do read up on extension functions, lots of limits.. e.g. they musst be static functions, and so cannot reference members. Also, unlike member functions, they cannot actually access private static members.
Does anyone want to help me get started on making my game?
no
sure, but this is the coding channel, what do you need help with?
Anyone know why i cannot rreference rigid body in my code?
because you are spelling wrong and your !IDE is not configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
heya folks, im having an issue with trying to get an object pick up mechanic working, its giving me an "identifier expected error" for this one part of the code, any ideas?
Same deal, you need to configure VS beforehand
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
(This step is required to get help here)
cheers
I cant find the preferences tab
In the Edit menu of Unity
In Visual Studio, open the "Solution Explorer" tab (menu: View > Solution Explorer), and post a screenshot of it here
Close VS, open a script from Unity by double-clicking it
This should open VS automatically