#💻┃code-beginner
1 messages · Page 413 of 1
public Vector2 maxPosition; // Maximum spawn position``` yes you should be able to assign these in the inspector
true, but the pipes spawn in the middle
hmm ok lemme try
debug randomPosition before u use it
right below this debug the value to see what shows in teh console..
Debug.Log(randomPosition);
Not sure, do the pipes spawn in the middle in the original Flappy bird? I would suppose, no.
GameObject spawnedObstacle = Instantiate(obstacleToSpawn, randomPosition, Quaternion.identity);```
his instantiate method uses the randomPosition
im not sure how they'd always be in the middle
look when i debug the randomposition
unless his values in the inspector are set up wrong
ya, thats fine.. thats not middle
i see -4 in there
By "middle", they mean at neither the top nor the bottom
look at where the pipes are
well they need longer pipes. and more extreme values
@umbral rock That's the reason of me writing [this](#💻┃code-beginner message)
yes but i dont understand what u mean by it, what is wrong with my code?
this is my spawner inspector
i think its more of a setup issue
ur prefab should be something like this..
really long pipes off the top and bottom.. and a gap in the middle.. the middle point is ur position.. then u can position it anywhere on the Y
and the pipes will extend off the screen bounds
the green + is the pivot (center)
Because I want it to travel a specific distance/do a easeInOutBack motion.
or... if u dont want em on the bottom and top u can do the same w/ two prefabs
just make sure they extend farther down like the double version does
what? i dont understand, what should i do with my prefab?
The 1st variant was fine, but doing this with two prefabs sounds more accurate to me. Also I doubt it would take much more time for you @umbral rock
its just the instantiate thats wrong? idk about prefabs but if u look at my game u can see pillars spawning in the middle of the screen wich shouldnt happen
how does that have something to do with prefabs?
They were just moving further, assuming you have already understood everything we've mentioned
it means set up ur prefabs like this..
Do you understand what I'm talking about [here](#💻┃code-beginner message)?
i made 2 for example (1 for the top and 1 for the bottom) .. the pipe is a child and extends from teh center... and way off the screen
if i set the spawn values to 0 then the pillars spawn perfectly on top of my view wich i want, but i want them to also spawn at the bottom, thats why i use random.range, but the problem is that my pillars are spawning between 2 values wich is the result of my pillars spawning in the middle
sooo when i set the position.. im setting that center position... no matter where i put it the pipe would extend off the edge of the screen
u mean having a spawner for the top pillars and a spawner for the bottom pillars?
no lol
no..
whut
u can use the same spawner and chose to spawn w/e prefab
I would like to ask everyone for some help. I am a beginner and while learning a tutorial on making a character move, I found that when obtaining the input system values, the character automatically moves to the left as soon as I run the game, even without any input. The input values obtained in the red box in the screenshot show no input, yet the character still moves by itself. I also added a stick deadzone to the input, but the character still moves on its own without any input. I sincerely ask for everyone's help to find out what the reason could be.
the main point is the prefab ROOT object.. is centered.. and the sprite then stretches from there down past the screen edge..
Maybe show the code, log the value being used to move, etc
yes but how is this a fix for the pillars spawning in the middle
if the edge of the pipe is really long.. it doesnt matter if u spawn it in the middle.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.PlayerLoop;
public class PlayerController : MonoBehaviour
{
public PlayerInputController inputControl;
private Rigidbody2D Rb;
public Vector2 inputDirection;
public float speed;
private void Awake()
{
inputControl = new PlayerInputController();
Rb = GetComponent<Rigidbody2D>();
}
private void OnEnable()
{
inputControl.Enable();
}
private void OnDisable()
{
inputControl.Disable();
}
private void Update()
{
inputDirection = inputControl.gameplay.Move.ReadValue<Vector2>();
}
private void FixedUpdate()
{
move();
}
public void move()
{
Rb.velocity = new Vector2(inputDirection.x * speed*Time.deltaTime, Rb.velocity.y);
//人物翻转
int facedir = (int)transform.localScale.x;
if (inputDirection.x > 0)
facedir = 1;
if (inputDirection.x < 0)
facedir = -1;
transform.localScale = new Vector3(facedir, 1, 1);
}
}
the pipe would extend off the page...
code is here
ur random range is working..
in the code.. and in the clip u shown.. its not broken
How to post !code (use the large code blocks guide rather than the inline guide if you've got more than a few lines of code to share)
📃 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.
#💻┃unity-talk message #💻┃unity-talk message i posted this in unity talk but got no response so ill try here
ahh ok, yes now i understand yeah, but what if i dont want the pipe to be so long? what can i do?
adjust ur range...
maybe have 2 ranges.. 1 range for the top section of the screen
and 1 range for the bottom
if u dont include the middle it'll never spawn in the middle
aah, so that u have minPosition/max for the top section and a minPosition/max for the bottom
yes
and maybe have 2 functions to call (thats the easiest)
or.. u can randomly pick 1 of those ranges even 😄
i have a tutorial here and he just adds a transform.position and then + the ranges
could that work in my project?
sorry my fault
if it works for him it'll work for u
ait, i'll try it, thanks alot for the help, cant thank u enough!
private void Spawn() {
Vector2 randomPosition;
bool spawnAtTop = Random.Range(0, 2) == 0; // Randomly decide whether to spawn at the top or bottom
if (spawnAtTop) {
// Generate a random position within the top bounds
randomPosition = new Vector2(
Random.Range(minPositionTop.x, maxPositionTop.x),
Random.Range(minPositionTop.y, maxPositionTop.y)
);
} else {
// Generate a random position within the bottom bounds
randomPosition = new Vector2(
Random.Range(minPositionBottom.x, maxPositionBottom.x),
Random.Range(minPositionBottom.y, maxPositionBottom.y)
);
}
altho u creating random X positions too
not sure how that works out for the type of project ur doing
this is my debug log
left and up
code like this private void Update()
{
inputDirection = inputControl.gameplay.Move.ReadValue<Vector2>();
Debug.Log("inputDirection: " + inputDirection);
}
Do you perhaps have got some drifting on your controller?
Also, post code correctly please #💻┃code-beginner message
https://gdl.space/ayedubuxed.cpp like this so sry about that first time come here for help
I didn't press anything, but it keeps getting this value by itself.
If you press anything, does it change?
When I press multiple direction keys simultaneously, there are some changes, but they are quickly overridden by the continuous directional input values, causing the character to move to the left.
Show your action composites and bindings. Here's an example
anybody know how i can check for a collision and than delete the gameobject?
pls ping me if yes
Finish the statement ||- you're missing a closing parenthesis )||
ok i try
collision.gameobject is still not working
Also, this should be done in some collision physics callback function
You probably ought to lookup a unity tutorial on collision
alr
u mean this ?
You've got multiple bindings for your Move action. Perhaps one of them is throwing false positives?
I followed the tutorial exactly, and my configuration is the same as in the tutorial. I just don't understand why I'm the only one having this issue, lol.
Use the input debugger to see what input is being fired https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Debugging.html#input-debugger
is there a way to tell whether a button is pressed or not via script? (not through editor)
i swear there was a button.clicked condition
Maybe you've got a controller with the stick being held that makes your character move - your move action consists of multiple buildings: gamepad keyboard, xr and joystick.
yep u were right. I just deleted all the other controllers except the keyboard, and the values returned to normal. Thank you so much, brother.
Assuming you're using ui button, these would be the available members https://docs.unity3d.com/2018.2/Documentation/ScriptReference/UI.Button.html
Hey I have a problem, I don't understand why this doesn't work. What should happen is that class 1 start the GameStart function in class 2 and then in class 2, the GameStarted bool is set to true. However when I try it, it sets true in the first class but not in the second so the game just never starts
void Update()
{
if (Input.GetMouseButtonDown(0) && !GameStarted){
GameStarted = true;
var instance = new DriftComponent();
instance.GameStart();
}
}
void Update()
{
if (GameStarted){
//never happens to be true for some reason
...
}
}
public void GameStart()
{
MoveSpeed = 50;
Drag = 0.98f;
SteerAngle = 20;
Traction = 1;
GameStarted = true;
Vector3 MoveForce;
}
Unless the second script is a mono behavior component, the Update function will not be called - we don't instantiate new components in Unity but rather Add Components to existing game objects.
It is a mono behavior component
i dont think this is the right one lol
Where are you adding the component? Is the game object with the new added component active in the scene? Is the component enabled? @sleek gazelle
yes
left is the name of a button
i wanted somehting like
if (left.clicked)
{
Left();
}
did you read what OnSelect does?
i did
should i use OnClick instead
wait no i cant read
it is a method and it does not return a value. that should not even compile . . .
oh
Cross posted from #💻┃unity-talk message
Something about this is causing a memory leak it seems. Anyone got any idea why?
> private void AddTechElement(TechType tech)
> {
> var itemUI = techSlot.Instantiate();
> itemUI.Q<Label>("TechSlotDescription").text = tech.techDescriptionShort;
> itemUI.Q<Button>("TechSlotButton").text = tech.techName;
> itemUI.Q<VisualElement>("TechSlotImg").style.backgroundImage = Resources.Load<Texture2D>(tech.techImgPath);
>
> Button choseTechButton = itemUI.Q<Button>("TechSlotButton");
> choseTechButton.clicked += () => ResearchTech(tech.techName);
>
> techListElement.Add(itemUI);
> }
> private void ResearchTech(string tech)
> {
> Debug.Log("Tech chosen:" + tech);
> ResearchTech(tech);
> AvailableTechs.Remove(tech);
> CompletedTechs.Add(tech);
> techListElement.Clear();
> }
!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.
then you weren't getting a memory leak you were getting a stack overflow
probs, I ain't got a clue
Hello guys, im new to this and Im following a tutorial, anyone knows why the squares (enemies) shows on the scene but not in game window? thanks
correct terminology is important. by saying memory leak you had me looking in completely the wrong direction
Sorry, my bad. Saw a lot of people mentioning it in the results I got when searching up the error message
maybe its because they are behind the background
How Can I know?
on yeah is that
i know linerenderer points dont lag but it still scary to keep 1000 of them with thousands of points each preloaded
public void OnPointerUp(PointerEventData eventData)
{
//InfiniteMode?.Invoke();
InfiniteMode(this, EventArgs.Empty);
Debug.Log("The mouse click was released");
}
Why do I get this error Object reference not set to an instance of an object about the this?
because InfiniteMode is null ?
The function exists in another script
Debug.Log it
//InfiniteMode?.Invoke();
I tried this too
you have commented out code that safely checks if InfiniteMode is null before triyng to invoke it
You have not given any context, so I have to guess that InfiniteMode is an event member
OHHHHHHHH
I understand
It works
Thanks
public void OnPointerUp(PointerEventData eventData)
{
InfiniteMode?.Invoke(this, EventArgs.Empty);
Debug.Log("The mouse click was released");
}
Did this and now I got no error
But the event is never catched anywhere 😢
yes, because it does nothing if InfiniteNode is null. You have to ask yourself why was it null in the first place
Idk cause it exists here
static void main(){
var publisher = new InfiniteModeButton();
publisher.InfiniteMode += InfiniteModeStart;
}
static void InfiniteModeStart(object sender, System.EventArgs e){
Debug.Log("Event Catched");
}
Do you run main() anywhere? Because Unity won't be running that
that is the method declaration. not the event declaration
and an event with nothing subscribed to it is actually null
No but I saw that somewhere on Internet and when I put it in Start it doesn't work either
You aren't making a console application. main is not your entry point, Unity is. If you want this to happen when the object starts, put it in Start.
It is in it rn
void Start()
{
var publisher = new InfiniteModeButton();
publisher.InfiniteMode += InfiniteModeStart;
}
What is InfiniteModebutton?
Show your entire script.
The class of the event invoker
Right
Is it a component
Hmmmm idk
This makes no sense
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class GameManager : MonoBehaviour
{
public static string Gamemode = null;
public static bool GameStarted = false;
// Start is called before the first frame update
void Start()
{
var publisher = new InfiniteModeButton();
publisher.InfiniteMode += InfiniteModeStart;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0) && !GameStarted){
GameStarted = true;
}
}
Do you have any errors in your console
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using System;
public class InfiniteModeButton : MonoBehaviour, IPointerUpHandler, IPointerDownHandler
{
public event EventHandler InfiniteMode;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
//OnPointerDown is also required to receive OnPointerUp callbacks
public void OnPointerDown(PointerEventData eventData)
{
}
//Do this when the mouse click on this selectable UI object is released.
public void OnPointerUp(PointerEventData eventData)
{
InfiniteMode?.Invoke(this, EventArgs.Empty);
//InfiniteMode(this, EventArgs.Empty);
Debug.Log("The mouse click was released");
}
}
yes
So maybe you should post them
var publisher = new InfiniteModeButton();
publisher.InfiniteMode += InfiniteModeStart;
local variable, so goes out of scope
My bad, I had
After that fix I don't anymore
But I never get the "event catched" in the log
cannot new a MonoBehaviour
I'll try to make it public
So I just remove MonoBehaviour?
If you're not getting any more errors with this code then it seems you have no instances of GameManager in the scene because that Start method definitely throws one
as uoi are not using Start or Update, yes
Ok
I do
If it's not a MonoBehaviour, it can't be a component
You can't put it on any GameObjects
Presumably, you do want it to be one
So, what I am trying to get you to see is the error specifically saying that you cannot create MonoBehaviours with new
My crystal ball says that there's an object in the scene that has this properly as a component, and that throws the error. newing is just an attempt at referencing it
And if you aren't getting that error, then you also don't have a GameManager in the scene
Yes, that's definitely a problem. I'm guessing there's many more
Yeah someone said that
but idk how to do without new
I swear I do
I have no error but a yellow thing
Then are you getting a message in your console that says you can't create a MonoBehaviour with new
That says:
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
UnityEngine.MonoBehaviour:.ctor ()
InfiniteModeButton:.ctor ()
Yes that
Yeah but no error
Okay, it's a warning, not an error
I thought you were talking about big red thing sorry
but it is still a problem
Yeah sure
Why are you trying to create a new InfiniteModeButton in Start
why not just reference the one you already have
Cause now I have an error
When people were saying that doing new to a MonoBehaviour was a problem, it didn't occur to you that a warning that says "You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed." might be somehow related?
Non-invocable member 'InfiniteModeButton' cannot be used like a method.
well I'm just dumb
sorry again about that
What are you trying to do
what is the line that gives this now
InfiniteModeButton is not a function
why are you trying to call it like one
Kinda new to C#
turn this
var publisher = new InfiniteModeButton();
into
public InfiniteModeButton publisher ;
and fill it in the inspector
I don't know all the syntax yet
Now it wants me to add }
did you move the line outside of the Start method?
Instead of guessing, you should probably continue with basic syntax tutorials.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thanks u so much!
you really do need to learn some C# basics
I know, I have already watched some of them but I don't remember all of them
This is why watching them is not a good way to do it. Take a written course. There are many. Microsoft has their own, w3schools has one, tutorialspoint, etc
Thanks
one other word of advice, don't just blindly copy code, that road only leads to a world of pain
Hello! When I load the scene, lighting breaks. How can I fix it?
Check in a build. There's an editor bug where loading the same scene again in the editor doesn't properly load the lighting settings
It's probably broken there too.
When you enter play mode, Unity generates lighting data for you if it doesn't exist.
It won't do this when you switch scenes, or at all in a build.
If it doesn't happen in a built version of the game, you can ignore it. I don't remember if they ever fixed that in a later version
so you get a scene with no ambient lighting
You can go to the Lighting tab (window -> lighting or ctrl+9) and create a lighting settings asset. Uncheck both of the "global illumination" options and then hit Generate Lighting
this should be fast, since it's doing very little work
i have a little pronlem so i have my transform for my muzzl flash on my gun but when i animate with the gun the game object doesnt move along
Make the muzzle flash a child object of the gun
i did
If it's a particle system, make sure it's simulating in local space
its not a partical system its just a spawn locatuion of my cartrigde
anyone tried using easysave for chunk load/unload system like in minecraft before?
hey im trying to make a canon and i want it to shoot my prefabs. i managed to instantiate my object and apply a force to it but how can i automaticly add the force to the forward direction of my canon and how would i give it an angle so it doest shoot straight up forward?
Instantiate returns a reference to the object it made. You can spawn in the object and then set its velocity
wdym just too setthe velocity of the prefab itself?
No.
digi said to spawn the object and then set its velocity
the velocity of the newly-created object
oh ok
i referenced the rigidbody of my prefab in the canon script and used the addForce method so i wouldnt need another script. it adds force to my object but in the wrong direction and i dont want to set it individually so is there a way to automaticly rotate the force to my canon?
Is your canon facing the direction you want it to fire in?
Remember that Rigidbody.AddForce interprets the vector in world space.
So if you use a constant direction, it's probably wrong
its y rotation is set to -90 and its a child of my ship so
So if it's facing the direction you want it to fire, then you can use that direction for your force
transform.forward gets the direction the object is facing
transform.forward is a vector3 isnt it?
yes
is there an easy way to modify the y axis? or better add the force at an angle?
if the canon is at x or z rotation 0 but the model itself is angled, its not exactly the correct direction
How do you decide where to create the cannonball?
Did you add an empty "fire point" object?
no it just spawns it at the pivot of the model which alligns with the start of the barrel. if the object get launched at an angle it flies through also the ship is far away so you wont notice it as it just fires at my island
that sounds very awkward; rotating the cannon model would make it flip into the air
consider doing this. you can position and rotate the object exactly the way you need it
wdym?
If the pivot point is at the end of the barrel, rotating the model will make its pin around the pivot point
the pivot is centered but it happens that the barrel on the back just fits perfectly
wheeee
th closed end bro
well that that sounds doubly wrong
you want the cannonball to appear at the end of the barrel
this will solve your direction problem and make it easier to control where the cannonball comes from
the closed end of the barrel. where the ball normally would launch. it has no collider so it doesnt matter but i want the transition it would look very akward if my projectile just spawns right at the tip of the barrel
regardless of where you want the cannonball to come from, this will make it very easy to adjust the direction the ball fires in
ok but if i have my cannon script on the empty object, and i add the force to the referenced projectile does the force direction change depending on the rotation of the empty obejct?
if your force vector is based on the direction the object is facing, yes
var force = firePoint.forward * shotForce;
for example
so using transform.forward would even launch the projectile on the x rotation i want?
transform.forward is a world-space vector that tells you which direction is "forward" for transform
notably, that would be the transform of the object your component is attached to
(that's what the transform property gives you)
So that would be wrong, because you'd be using the transform of the cannon itself, not the fire point
bruh but when i attach the script to the firepoint?
It would then be correct.
you don't have to "bruh" me. I am trying to explain what will and won't work.
yeah sry but i said that the script is attached to the empty object soo
but thanks i apreciate your help
ah, I missed that; my bad
np np
I would want to put the cannon component higher up in the hierarchy
but i need it to be a child of my ship cause it gets rotated to a target point in my scene where the projectiles should be launched at
Right -- you might do this
- Cannon <-- just the "cannon fire" component
- Model
- Fire Point
- Model
i think i dont understand. i have my ship, and my cannon as a child, so it rotates when the ship rotates
Yes, so you'd parent Cannon to the ship
Parenting the model to an empty object makes it easy to adjust the position and rotation of the model
it lets you change the apparent pivot point for when you rotate the entire Cannon
i dont get it xd
i have my ship on top, bc it gets rotated the way the cannons should. the cannons are the childs of my ship.
Yes.
- Ship
- Cannon
- Model
- Fire Point
- Model
- Cannon
ohh so the cannon is a parent with the firepoint and the model "childed" to my ship i think i get it
why does this code insist that 'PlayerMask' doesn't exist when i try to use it in raycast?
void Start()
{
LayerMask PlayerMask = ~LayerMask.GetMask("Player");
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.R) == true) {
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.up, 3f, PlayerMask);
Fire(hit);
}
because PlayerMask is a LOCAL variable to Start
Hi, I am trying to understand unity by building endless runner.
But can't understand why the path spawn at a distance from the player ? Help please.
The tiles-spawn file:
⏬
Large 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.
also you should not crosspost. Should delete your post in #💻┃unity-talk
how do i code in unity? i got it installed properly and want to code a sidescrolling adventure game
You'll have to learn some Unity first. I would recommend their official learning site: !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Oh okay
Can you tell me what should be my promt to search for to this ? I googled it, found nothing useful.
Hi, I know this isnt exactly code, but how would you accomplish having a prefab house with only 1 room? (player would have access only 1 room, others will be just nothing - for less lag) - how do I make the windows look the same for the 1 real room and the other fake rooms from outside, but from the 1 room being still able to see outside normally?
If I want to edit material properties via a script, in both runtime, and edit mode (Via [ExecuteAlways]) Whats the proper way to handle it?
I would still probably recommend having a separate runtime and editor-side script to handle it rather than writing one ExecuteAlways function to do both. Chances are you'll need to do some slightly different things in each (especially when dealing with materials that could be an asset or a runtime clone of one)
Hello, I've been looking for the right room to make a post asking questions about Unity development but I can't find it. Does anyone know it, please? There is 'DOTS" but i don't think that'sthe right one
You should ask the questions about DOTS in #1062393052863414313
#🔎┃find-a-channel for whatever channel is the most relate to your problem
Well, I guess this isn't the right salon. Besides, I didn't dare post about such a stupid question
What question?
Thanks, that's what I did but I couldn't find anything adequate 💀
If there is no channel for it then #💻┃unity-talk is the place
My question is what is DOTS. Is it that ? : https://unity.com/fr/dots
That way I know if I'm off-topic or not in relation to the problem I want to explain so that people can help me.
In fact, the problem I'm having with Unity is so long to explain that I'd have preferred to present it in a room where you can make posts. And "DOTS" seemed to be the most suitable. But I think this not the best room for that.
Oh so i guess there is no room where we can make post about anything ? Just brut text ?
Yes, this is a question about DOTS, so you should ask it there #1062393052863414313
And, yes, the link you've sent is about DOTS
DOTS is basically a different way of structuring objects in Unity so that you can have a whole bunch of simple things running at once. If you have a specific question about how to use it, #1062393052863414313 would be the place
why would you think that a question about #1062393052863414313 does not belong in #1062393052863414313 ?
Ok thank you
Thank you for the explanation
I wasn't clear, but basically I've got a problem with Unity. And on the discord server where I usually ask for help, there are dedicated room where you can only make posts. We don't ask for help on threads like this one.
My mistake was to adopt the same logic here. So I was looking for a room where we make posts to ask my question. I found "DOTS". I wasn't sure I could present my problem with Unity here because the term "DOTS" was unfamiliar to me. And on "DOTS", I didn't dare make a whole post to find out what it meant because the question seemed silly to me.
But now I've got my answer thanks to @polar acorn. I'm going to go to the other room. It's a shame we can't make a dedicated posts. Thanks again to everyone! Sorry to have polluted the discussions with my stupid intervention
I still do not understand your logic or argument, you have a question about Dots but dont post it in the Dots channel, you were directed to #💻┃unity-talk for general questions and yet you still posted your dots question in a totally unrelated code channel
Hello friends, I have a problem. My game works fine in the editor, but when I compile the game for PC or Android, most everything works, but I guess I can't get the information I saved in json format as I want. When I compiled it for PC today, I entered the game and caught an animal, saved the game and logged out. When I entered the game again, I could not access some of the things I saved, for example, the Transform location was in the place I saved, but there was no animal caught. But it was recorded in json format. When I went into the editor again and looked, I could see everything I saved in the compilation there. I think my problem is that it doesn't read from json because I didn't make certain settings. Can one of you send me a screenshot of the player settings or tell me if you guess the source of the problem?
don't crosspost
ok
You know there is a general discussion post in #1062393052863414313 as well. You don't have to make an actual post of your own
Please reread my answer. As for your first point, that's because I didn't dare ask a question that seemed stupid to me. As for the second, if when you say "you were directed to unity-talk", you are referring to @\digiholic message. You'll notice that I stop talking about dot just after and the conversation ends shortly afterwards.
Oh I didn't pay attention to that. Thank you very much !
if i use transform.forward for sth how is forward defined? like which axis?
anyone knows how to fix this?
could u send a screen shot of the inspector with the Object which has the TFUtils script attached?
ok
that isn't what they were asking for. but what they were asking for wasn't even necessary anyway. we'd need to actually see your code to determine what is wrong if you're too lazy to go through the steps in the link i gave you
is this script attached to a GameObject?
what changes does a pivot make?
like sometimes the image goes up and down but why not every single time?
send a screenshot of the inspector pls. theres propably a public value where the object or value needed isnt set/referenced
- this is a code channel
- there's not enough context to be able to answer this question
ummm its toooooooo long
,_,
damn my unity crashed!
wait
how to correctly share !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.
wait so to share code need this?
right?
you need to read the bot's instructions for sharing code, yes
ohhh this better yo
still not what i asked for lol. this script should be attached to a GameObject. send me a screenshot of the GameObject pls
i don't see why you are even bothering to ask for that when we don't even know what is null yet since we haven't properly seen the code
ah yeah im stupid seeing the code is way smarter thought of an Object or sth like that which isnt attached
yo chill ,_,
and its not a (GameObject)
game works but when i log in using this pakage photon give me datamanger error and these creepy things ,_,
public class CanonMain : MonoBehaviour
{
public GameObject projectilePrefab;
public float projectileSpeed;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) {
LaunchPrefab();
}
}
void LaunchPrefab() {
Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
projectilePrefab.GetComponent<Rigidbody>().AddForce(transform.forward * projectileSpeed);
}
}```
could somebody tell me why my addforce is changing litteraly nothing at all?
you probably want to use ForceMode.Impulse for a one-off force
also you're adding force to the prefab not the instantiated object
ok ill try thought this was standard
wait i need to def unity engine?
or what ,_,
man iam noob lol
that is entirely unrelated to your issue mate. we're still waiting for you to share your code
nah im just noob to and have a problem xD
the code of tfutils.cs?
obviously yes since that is where your error is
alright wait
i have been
how do i have access to my instantiated object?
Instantiate returns the instantiated object
im a complete noob wdym xD
there are beginner c# courses pinned in this channel if you do not know how to use the return value of a method
@slender nymphstupid Q lol
how is this not moving my bullet in the position of my mouse? is just going anywhere
how can i share the code from there again 🙂
you save it and share the link
thanks i watched the create with code course lately but i didnt see the generell scripting one
!code 👇
and also https://unity.huh.how/screentoworldpoint. check how to use this for a perspective camera since I'm assuming you are not using an orthographic once since this does not appear to be 2d
📃 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.
since the error is on line 239 that means it is if (data.ContainsKey(key))
there are only two objects on this line that could be null data and key. you need to determine which is null and then look at the stack trace to see where you are calling this method from to determine why it is null
ohh
also why do you have a folder named Assembly-CSharp? is this a decompiled project?
yup ,_,
i know break rules
lol
it is against the rules to assist with stuff like that
i know
,_,
iam crying now ,_,
yeah i'm blocking you now. don't need the spam or the willful rule breaking 🤷♂️
If you know, then why did you ask?
hmmm maybe know anything from unity ._. tried yt but its u know basic project lol
like how to add
and these things ,_,
alright fine i will delete this project
gg to me ._.
All i will say is !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
,_,
Maybe !learn the basics in a proper project first. Then if you have any issues with whatever you're doing, look for a community that supports modding or whatever you're doing.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
hey guys im currently in a game jam and trying to make a game about snakes and im making a snake battle royale and im trying to get a snake where it follows the mouse like slither.io and i have that its just i need help with segment rotation so like every sement shoul lepr its rotation to the next one do you understand becuase this is what i have now
public class SnakeMovement : MonoBehaviour
{
public float MovementSpeed;
Vector2 MousePos;
public List<Transform> SnakeSegment;
public float SegRotTime;
void Start()
{
foreach (Transform t in transform.GetComponentsInChildren<Transform>())
{
if(t.gameObject != this.gameObject)
{
SnakeSegment.Add(t);
}
}
}
// Update is called once per frame
void Update()
{
SnakeFollowMouse();
}
void SnakeFollowMouse()
{
MousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = Vector3.MoveTowards(transform.position, MousePos, MovementSpeed * Time.deltaTime);
Vector3 direction = Input.mousePosition;
direction.z = -Camera.main.transform.position.z;
direction = Camera.main.ScreenToWorldPoint(direction) - transform.position;
transform.rotation = Quaternion.LookRotation(Vector3.forward, direction);
}
}```
im moving the snake as a whole right now but i want the indual senments follow one another smoothly so i was just wondering how can i accomplish this?
you would want to separate the objects, child objects immediately follow the position and rotation of their parent, so if you rotate the parent, then the children get rotated along with it
I would personally have some component that controls individual segments, have that component get a reference to the segment in front of it so it can follow at the desired offset and smoothly rotate to face it
oh okay
@slender nymph
like this?
bc if idont parent them then its gonna be very disorganized
i feel like you didn't read any of what i just told you
so if that is the only thing you took away from what i said, why would you think i would say yes to your "like this?" question when you are doing exactly what i said you shouldn't be doing
you didn't even change anything. that hierarchy structure is exactly like it was in the first screenshot
eyah your right
wait but box friend
how would i spawn snake object then?
like as whole because if i want to make a prefab of a snake and its not a parent then its gonna be alot harder to spawn them
spawn snake root object. have that object spawn its individual segments in a loop so that they are not directly connected
would there performance issues if i were to spawn 100 snakes?
it would be exactly the same "performance issues" if they were 100 snakes with the segments as children since it's still the same number of objects doing the same things
ok
if you make them child objects, then each time you rotate any of the parent objects you will then need to rotate the children in the opposite direction in order to ensure that they aren't all rotating exactly the same which i believe is your current issue
oyh
ok thats sounds tricker
i dont have that typoe of time imma just go with the first method
@slender nymph
ok so i did through script now justa quick question can i accomplsiht he same thing unsing joints and would that be easier or should i just it through code?
what imean is the rotation part
that's going to require multiple rigidbodies. do you need physics for this?
mabey noit sure c i just need these guys to follow the mouse direction then each segment should rotate the way i wnatedto like i said earlier then the way i need them to attack is like a curve
so i dont think so
bc its a top down game
so theres no ground
so no id think so
i dont think so
can i just give the rigidbody 0 graviity?
what would you reccomend in this case
i already told you what i recommended you do
if you want to use joints, go for it. but each segment will need its own dynamic rigidbody
if you go that route, you can switch back to making the segments children objects since rigidbodies will move on their own (provided you aren't constraining their movement)
and also remember that physics is not just gravity.
ok thank you
ill try the first method
Hello!
I need help with the old Input Manager (not the new one)
It seems to have support for around 30 axis of joystick input. I'm trying to understand what all axis are for past the first few ones. 2 of them for a stick, 2 of them for the other stick, 2 of them for dpad, then there's some of them mapped to the triggers.
Are there axis dedicated to the face buttons too?
(Yes I know you can use button for face buttons, but I'm in a situation where this is not possible)
I can't find reference to which actual input each of those axes are mapped to and reference I find online is lackluster or contradictory. I also do not see them documented!
Hello. I'm a rank beginner, and I'm currently trying to make a pause menu. I've followed a tutorial, but I'm getting this error, and I'm not entirely sure what's wrong with my script, beyond what it is telling me.
configure your !IDE so you don't make silly spelling mistakes like that
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
C# is case sensitive. A lowercase lettor in the wrong place makes something completely different that the compiler will not recognize
@slender nymph i have thgis code to follow towards the mouse pos but for some reason my z position keeps lepring to negitve 10 causing my snake to go off screen
I don't think I've got any mistakes in this, but I may be wrong.
Should I be using this dropdown menu if I already specified the joystick index in "Positive Button" ?
You would think wrong
I mean... you got an error. Errors do not lie
Also, it is clearly capitalized incorrectly
I mean, I know that, logically. But which is capitalized wrong?
Install visual studio tools for unity if you're using Visual Studio this will avoid this kind of headache for you
NO property is lowercase for the second word
https://docs.unity3d.com/ScriptReference/Time-timeScale.html unity documentations!
It showed exactly which in the error
Literally the word is in quotation marks
"timescale" does not exist
Again, there is NO property that has a lowercase second word
There is some inconsistency in the FIRST word. And argument about which is right. But across the board in unity, the second word is capitalized
Do what you were told above and configure your ide, it will underline errors and even tell you how to fix them most of the time. It is VERY helpful
I have an issue where either my input is detected on all controllers, or none at all
I don't know how to do for my virtual axis to be detected only for joystick 1 or joystick 2
Ah, it was timeScale, not timescale. Now I'm running into an issue where the pause menu is just stuck up, though.
and I have to say the documentation about this is really confusing. Most of the forum posts I find are about the new input system and posts about the old ones are seemingly going missing
But I figure out there must still be some people around who have experience with the old system to help me? 🙂
Update is not called when timeScale is 0
how can i have rounded corners on a box collider/tilemap colldier? these sharp corners are giving me lots of trouble, that would likely solve it
Should I go in another channel maybe?
You cannot on a box collider. I do not believe you can on a tilemap.
I thought this would be a beginner question but maybe I misjudged and it's not
i see. so what to do?
I do not know the answer, sorry. Maybe try #💻┃unity-talk
Uh. Hmm. So how would I fix that in the code?
Maybe a squashed capsule? Or a custom shape.
May be an xy problem though. Is the issue that the player is catching on the map? Maybe make thr PLAYER a capsule
i could do that, but the player is rectangular so the sides would just clip through the walls
You know what, I think I am wrong. Update should still run
Hmm, not sure what you mean, sorry.
the player is a tank, which is rectangular. a capsule collider can't fully cover said rectangle without being larger then it
Yeah, that's the confusing bit for me.
Ah I seeeee. I wonder if it would be worth it to just do a convex mesh.
Alternatively, do a slightly larger box collider that is a trigger and like... reduce speed when it collides, notifying the player they are too close to a wall or something
Are you putting your PauseMenu gameobject into that pauseMenu public variable?
Like the same object that has the component script?
hey guys how can i keep objects apart in unity 2d by a certain ditance at all times?
bc right now i have that code in the if statement
except the objects still move closer to each other bc they have to hit that limit before stopping to moe i was just wondering is there a way to keep a constant distance between objects?
you check if the distance is greater, then it moves closer. you don't check if it's too close to then stop . . .
you should do the opposite. if the distance is too close, move away. once it's at the distance, it won't move any more . . .
...Yes? I think? Do I need to change PauseMenu to pauseMenu?
This field. What are you setting it to in the inspector? Can you show the inspector?
so im trying to make a script that collects stuff when the player touches them
but i get these errors
heres the script
The variable score of iron has not been assigned. You probably want to assign something to score.
the error says you need to assign a variable on a certain script. you should probably do that (in the inspector) . . .
Not sure which you wanted, so I shared both.
is this always empty?
we just copied and pasted the text from the error . . .
yeah well i set the score variable but still does error
oh okay thank you
do you have more than one of those scripts in your scene?
also, is the error the same message or a different one?
hello, im doing bullet physics and im kinda stuck, so here is a question:
how would you make ricoshet/bounce check for a bulet at angle (please not an angle threshold)
same one
thats the only script in the object made by me
the other scripts were from the asset itself
thank you for the suggestion i had another question so im trying to get my snake segments to rtate and follow one another smoothly so i used the quaternion lerp function and it almoost works except the pices look likey they discornnect?how could i fix this?
You need to drag your pause menu gameobject into that slot in the inspector
no, i meant are there any other copies of that script attached to different GameObjects? if it still appears then there is another iron script that does not have score assigned . . .
Everything works the attack, but the player does not move. The animation controller is showing that it is receiving the input but the player just doesn’t move from its spot. The animation works just my player won’t move. Please help
!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.
Mmmm I love literal camera pictures of a computer screen.
It works! Thank you.
yeah a double whammy
wdym a bounce check ?
Isn't print screen built into most modern PCs?
larger the angle, the morelikely it will bounce/ricoshet
idk how i could make a toggle for it that isnt a angle threshold
Use a remap function from the angle to the percent chance of ricochet
that is angle threshold what i was talking about
Square map: when you reach edges, you switch map, stucked to deciding whether we'll use colliders or constant position check per step, any insights?
what does the error say?
the method does not take 3 arguments. so don't give it 3 arguments . . .
check the unity docs for the method to see the arguments and/or overload methods . . .
i dont know what im doing, anyone got any tutorials?
.lua was easier
everything is so complicated
: Unity how to _
if i want to learn how to code do i start aiming for something i want to code or just start coding the basics to figure out what im doing
you should start with beginner courses that go over the fundamentals, like the courses pinned in this channel
thank you
you might want to fix your IDE so you have proper syntax highlighting
its a lot easier to program when you can see visual patterns in the code itself
Your question doesn't make any sense then
But what I mentioned is not a threshold.
How do I do an if statement for if I click my mouse
Broblem solved by another rperson
if (Input.GetMouseButtonDown(0)) for example
@velvet kernelthere's a lot of overlap between regular C# and unity C#. Just start with the basics like a console application
you shouldn't expect yourself to become a pro right off the bat
you'll also need a little bit of knowledge on vector math if you want to do anything interesting with 3d
I'm sure you know this though
unity is pretty dang simple after you get the basics
modding depends on the game, really.
lets say a car game
entirely subjective
ik one that allows modding thats unity
just don't give up so easily. copy and paste some examples and rip them apart
I promise it's not as difficult as it all seems.
for now i only know how to open up the coding software
from then on its a big step thats twice as big as me
if yk what i mean
Is there a more efficient way to do this
sure, I was frustrated when I started out.
just take it one step at a time. there's hundreds of tutorials
the only improvement i could see is making the second one else if
lets say i want to start with modding how do i get the code i want to mod
can you learn how to paste code instead of taking a picture of your monitor please. it's easier for you, and the people looking at it
animator.SetBool("IsAttacking", Input.GetMouseButton(0))
depends on your definition of efficiency ^
Osmal's answer is fewer lines of code, but less efficient computationally
subjective. depends on the developer and how he designed the game.
which will probably be in his modding documentation
which you'll need to read
you start by learning to code
yeah, there's no way around coding. if you're going to mod, it's going to be code heavy.
i start by finding more motivation lmao
i'm being genuinely serious. if you want to develop a game or mod you need to learn to code
for me learning from a tutorial is much harder then someone explaining it to me
what do i even start with
text based tutorials / documentation
"static void Main(string[] args)" what does static and void mean
you can google that, and you'll get 100 answers
there's also a dedicated C# discord to help you with the absolute basics
Honestly, don't worry about static for now.
Void means the method does not return anything
the entry point of a barebones application will generally be static 🙂
whys code gotta be so complicated
c# is very straightforward compared to lower level languages.
people in the 90's had it much worse
i need a online course where i can learn
I feel like that should be self-explanatory
where i can ask questions and someone answers 😭
my man, just copy and paste the examples on w3schools, read the 3 lines of text explaining it
and just play around with it
you've got to be interested to learn.
Just write down questions as you go through the courses I sent. Many will be answered as you go.
At the end, google two or three sources for each you don't know.
If it still don't know, 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
alr well
ill take your guys advice
but i dont think my brain is able to handle the amount of information coming in and is just turning off 3 seconds into watching a tutorial video
ill try tmr
im too tired for this rn
Don't use videos for now. But yeah, breaks are important. And so is repetition
oh alright
I'm trying to move object locate from script which belong to upper layer object. what shall i do?
want to move object is made by this : Instantiate (objDice1, new Vector3(diceBaseX,diceBaseY,diceBaseZ), Quaternion.identity);
also i have to use unity 2022.3.9
move object locate from script which belong to upper layer object.
I'm struggling to understand what any of this means.
When you say "upper layer object" do you mean a parent? Or sorting layers? Or what?
If English is difficult for you, use a translator
They probably want to move the parent but have not provided us enough code to differentiate what was instantiated
Im sorry for struggle english ,im studying it now
I want to move objects generated by "Instantiate" thing
var instance = Instantiate(...);
Move(instance);```
It would depend on your movement system but basically, cache the new instance and move those.
Could you give me example code to move Dice1 to (1.0f,2.0f,3.0f)?
var dice1 = Instantiate(...);
dice1.transform.position = new Vector3(1.0f, 2.0f, 3.0f);
var dice2 = Instantiate(...);
dice2.transform.position = new Vector3(3.0f, 2.0f, 1.0f);```
It worked! Thank you so much for helps!!
can someone help me create a script for touchscreen input?
if you need help with something specific about that, then Don't Ask To Ask
if you are asking for someone to actually do the work for you then 👇 !collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
use the new input system, create an action map for Touch Input, Generate the C# Class, then Get the input using ReadValue
this is a code channel
my mistake
can I make my collider a detection only one? As in nothing with a collider will interact with it physically, but I want to do something every frame a specific object (which has a boxcollider2d as well) is within this box. Is that possible?
make it a trigger. but is there a reason it needs to be an actual collider and not perhaps a physics query like an OverlapBox?
start by learning the fundamentals. there are some excellent beginner courses pinned in this channel
the fundamentals of code because this is a code channel
I have an Item script/class
At the moment I have 3 major item types, probably more coming in the future: equipment, scrolls, spells
Equipment is then further divided into: weapons and armor, which can each be divided further as well, like 1h weapon, 2h weapon, helm, body, boots, ...
For now this is all in my Item class, but I've realized I need to rework this now to add spells to my game, they will have a lot of different fields and won't use most of the fields the current items use. (Is field the correct term? Or attributes?)
So I'm planning to add 3 child classes for Item: Equipment, Scroll, Spell
Not sure if I should further divide equipment? How do I determine that?
Item abstract ScriptableObject
- Equipment abstract ScriptableObject
- Weapon sealed ScriptableObject
- Armor sealed ScriptableObject
- Scroll sealed ScriptableObject
- Spell sealed ScriptableObject
Hello, I am currently trying to write a custom component script for a unity, this is my first time attempting a custom script of this sort. My question about this script does not have anything to do with the game it is for so hopefully i can get help here.
I am currently having the component create a meshcollider component on whatever gameobject it is assigned to, i have gotten this part working, but i am now trying to have it automatically assign that meshcollider component to its own meshcollider slot "_modifierArea" as well as have it make that mesh collider both convex and a trigger.
I believe my current problem is that i have the code that does that second part in the Start() void, which only happens when the game is running, and I would instead like it to run whenever the component is added in unities editor. I am unsure how to do this though. someone has suggested i try putting that code in the constructor itself? I am not completely sure which part of this is the constructor, or how i would implement that. As when i try to copy the code out of the void Start(), unity throws errors saying that methods are not allowed in a namespace.
using System;
using UnityEngine;
using Utility;
using Game.Units;
using Ships;
// PlayerScript requires the GameObject to have a Collider component
[RequireComponent(typeof(MeshCollider))]
public class MapModifierZone : MonoBehaviour, IModifierSource
{
[Tooltip("The trigger volume used to define the area in which the modifier(s) is/are applied")]
[SerializeField]
private Collider _modifierArea;
[Tooltip("This name is used to differentiate from other sources of modifiers (e.g. Energy Regulators, Ammo Elevators, Drives) Make it unique from other modifier appliers, but the same across all zones of the same type (so the modifier doesnt stack to maximum unintentionally)")]
[SerializeField]
private string _zoneSourceName;
string IModifierSource.SourceName => _zoneSourceName;
// Start is called before the first frame update
void Start()
{
// Ensure the MeshCollider is set as convex and is a trigger volume
MeshCollider modifierAreaMesh = GetComponent<MeshCollider>();
if (modifierAreaMesh != null)
{
modifierAreaMesh.convex = true;
modifierAreaMesh.isTrigger = true;
}
_modifierArea = modifierAreaMesh;
}
// Update is called once per frame
void Update()
{
}
}
nvm
i got it
that always happens right as you ask for help xD
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IDropHandler
{
public GameObject Hand;
GameObject Hand = GameObject.Find("Hand");
public GameObject Table;
GameObject Table = GameObject.Find("Table");
!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.
public GameObject Table;
GameObject Table = GameObject.Find("Table");
This is not valid code. You can't declare 2 fields with the same name.
how do I fix this?
Hi all, is there a way to enable word wrap for the Unity console?
Don't declare 2 fields with the same name...🤷♂️
What's the intention behind that code?
but if I dont add that it says table is not defined
else if (gameObject.name == Table)
{
transform.parent = orginParent;
}
trying to get this to work
This is also not a valid code.
I feel like you're typing random stuff without any understanding.
orginParent is a variable i added before
I suggest you follow the beginner pathways on unity !learn and maybe learn the C# basics separately as well.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
but why wouldnt the else if portion work
- Share the whole script.
- Share the error details(a screenshot of the console would do)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I thought I already explained that this is invalid. You can't have 2 variables with the same name
i dont know where im making 2 variables though
Here:
public GameObject Hand;
GameObject Hand = GameObject.Find("Hand");
public GameObject Table;
GameObject Table = GameObject.Find("Table");
Do you have a typo with "orginParent"?
i had a typo when i was creating it so it didnt matter
2 vars with the name Hand and 2 with the name Table
I don't think GameObjects are considered a variable in Unity, right?
can you hlep me
Variables are usually assigned to datatypes, like string, int, char, float
no. this creates a variable called Hand. then creates another variable called Hand and assigns the result of the GameObject.Find call (which will fail in a field initializer) to that second variable
No. It's declaring it twice
oh
GameObject is a data type. every single class, struct, enum, interface, etc that you create is a data type
GameObject is a type like any others. And you can have variables of any type.
please fix my prob
This pretty much tells you what the issue is.
Again, I suggest you stop right there and go learn the basics properly
i im trying to compare a string and a gameobject
And how do you image that would work?
dude?
poorly
Worse. It doesn't work at all.
why ignoring me?
Stop pinging random people.
i dont know how to change it to work
i came here for hlep
If you have a question just ask it, and someone might be able to help
Learn the C# basics.
this is a code channel
i want to add 2D vector here how to add
i'm learning as i'm going
what channel i should select for that kind of hel
Well, it doesn't seem to work for you then. Maybe change your learning approach.
#🖱️┃input-system
and maybe bother checking the docs since this is clearly explained in the documentation
the problem i'm having with this approach is that im getting ahead of myself and going back to change things that ive already written
with newer concepts i dont understand as much
The problem is that you don't know that basics and writing code without any understanding of what it's doing.
well i understand most of what i've written
the top part that wasnt working was written by my friend as a suggestion
That's why I suggested unity !learn and/or go over the C# manual/beginner courses.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i'll do it after i fix this bug
but not enough, and not enough to recognize why what you've written doesn't work. you should really take that suggestion dlich has given
its gonna bother me untill i fix it
Well, then you're on your own.
We can't help you if you don't understand our help.
damn alr
If you're learning as you're going, you should be able to go to the C# documentation and read on the relevant topics, namely, types, and variable comparison.
I highly doubt you'll be able to understand it without learning properly some even more basic things though
main reason why i've jumped into things is because i learned python and i hoped it would be similar enough to be a crutch
obviously it was not
hey,
i have a little problem so i have a chest where i want to interact with but the interaction system is based of mesh collider so the problem is that i have two seperate colliders in the chest one for the top and one for the bottom my question is is it possible to sort of combine two collider into one?
It might've worked if you had experience with several different languages, like python, C++, java or something.
Knowing just one language(don't know how deep you know it), is far from being enough of a background, as your understanding of programming in general is limited to that language.
you could give the root object a rigidbody, that would combine both of the mesh colliders into the rigidbody's compound collider. then you can just null check hit.rigidbody and get the interaction component from that if it isn't null
also doesnt help that python is pretty far from c#
Yep
You can add a checkbox ui element to the panel and link it to your code.
ok thanks buddy
Ok now another question, the goal of this script is to have a zone on a map that applies an effect whenever a ship/player enters the zone. In particular i am wondering if having the component to define the zone be a trigger mesh collider will be an issue?
players need to move in and out of the zone, will a trigger mesh collider block this?
ok it seems that triggers are correct
if (Physics.Raycast(ray, out RaycastHit hit, interactionDistance))
{
if (hit.collider.gameObject.layer == 6 && (currentInteractable == null || hit.collider.gameObject.GetInstanceID() != currentInteractable.gameObject.GetInstanceID()))
{
hit.collider.TryGetComponent(out currentInteractable);
if (currentInteractable)
{
currentInteractable.OnFocus();
}
}
}
else if (currentInteractable)
{
currentInteractable.OnLoseFocus();
currentInteractable = null;
}
so here i need to check rigidbody instead
hey i have issue in my code
tell me
anyone??
Don't spam random people. Provide the necessary data by following the guide on how to ask questions #854851968446365696
bruh i want help
!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.
Then post your code and describe your issue instead of spamming random people
If someone knows how to help, they will
Unity related coding question. Yes.
okay
ive got this script and the problem is
the object deletes itself before particles have chance to play
i thought maybe there is a way to make it "sleep" one second before it deletes itself
lemme post a screenshot
I tried doing it using Invoke ("DestroyDelay, 1); but it just doesnt work
maybe u have some suggestion how could i do it so it waits 1 second before executing the Destroy line
so i have this block of code that successfully debugs but it doesnt set the panel inactive for some reason: ```
public void ClosePanel()
{
panel.SetActive(false);
Debug.Log("fgdfgfd");
}
i have everything set in the inspector it just wont work
Use a coroutine
how can i do that
You can learn about coroutines in the manual/docs: https://docs.unity3d.com/Manual/Coroutines.html
okay thank you!
Are you sure that panel is the object that you're looking at? Try adding it's name to the log or even pass it as the second parameter and click the message in the console.
okay
yeah it is 100%
it prints the correct name
it opens successfully but never closes when i hit the button
Assuming it's really the correct object, you must be enabling it somewhere after that.
Maybe add a log in that object's OnEnable/Disable to confirm that and see where it's enabled from.
im enabling it using an input
but disabling it in another script
Doesn't matter.
What's wrong with this line?
Also a pro tip: make your logs more meaningful, instead of printing gibberish.
You tell us.🤔
but theyre temporary
it doesent works
did you reference the rigidbody
Even so. You want them to provide meaningful info. If you have them in more than one place, gibberish is gonna be very confusing.
Look
How does it not work? Does it throw an error, or doesn't do what you expect?
well i usually only have my debugs one at a time but i agree, if there are multiple debugs then i should make them more meaningful
if its just 1 then its fine
he doesn't jump
Okay, and the debug log there prints?
btw you should use other.CompareTag("Floor") instead of other.gameObject.tag == "Floor"
yes
The issue is probably you applying the force only once on key press. That is not gonna move your object.
thx
np
also dont use Vector3 use Vector2 since your game is in 2D
doesnt really matter but its better for consistency
You either need to keep on applying the force in fixed update or use an impulse mode for it to have effect immediately.
i see, thanks
ForceMode2D.Impulse btw
{
GameObject myGameObject2 = new GameObject("Lvl" + level);
ren = myGameObject2.AddComponent<SpriteRenderer>();
ren.sprite = CamilaLvl2;
bc2d = myGameObject2.AddComponent<BoxCollider2D>();
rb2d = myGameObject2.AddComponent<Rigidbody2D>();
rb2d.gravityScale = 0;
bc2d.isTrigger = true;
}
private void OnTriggerStay2D (Collider2D collision)
{
string thisGameobjectName;
string collisionGameobjectName;
thisGameobjectName = gameObject.name;
collisionGameobjectName = collision.gameObject.name;
if (mouseButtonReleased && thisGameobjectName == "Lvl1" && collisionGameobjectName == "Lvl1")
{
mouseButtonReleased = false;
Create(2);
Destroy(gameObject);
Destroy(collision.gameObject);
}
}```
Hello guys! I got this script here. Basically when 2 gameobjects collide, i want to destroy them and spawn a new one. A new one does spawn, got all the components right, but the sprite isnt assigning to it. Does anybody has an idea?
Are you sure that the sprite isn't assigned? Can you take a screenshot of the spawned object's inspector?
This is a thing that i know I didnt do. Basically that gameObject is spawned inside of the script, and I add my script to it inside of the script. The Script of my Sprite is completly empty cause Idk how to assign them.
Wdym by "script of my sprite"?
But this is the thing here that I completly dont understand
Maybe instantiate a prefab with all the refrences assigned instead of creating a new gameobject?
and this prefab is like a copy of the script that alr has all assigned?
A prefab is a prefab. When you instantiate it, you create a copy of the prefab in your scene. With all it's references intact.
what are some use cases in which you might use the interface keyword?
Let me clarify a bit. So, by pressing a button, I spawn a gameobject. The image of the gameobject is being taken from where I stored the script (in Canvas). I added as a component my script, cause in the same script is a movement feature and I need it for my gameobjects. I added that script to the gameobjects and all the references are gone. How can I assign them back? Cause if in run time, if I assign them to both of my gameobjects, when colliding them, a new gameobject spawns that HAS the sprite
When you want to create an Interface obviously.
.. yeah but why use it? why choose it over an abstract class?
i dont get it
Either assign them manually, or don't do that. Don't add a component programmatically. Instead, instantiate a prefab that has the component with all it's references assigned.
i like to think of interface and abstract classes as c++ header files
It's a design question. Abstract class limits what you can inherit from, and you can only inherit from one (abstract)class. With interfaces you can implement as many as you want.
How can I create a prefab and assign those references in it?
ahhh i see
well what are the use cases for them? they seem pretty useless
That's totally different thing. C++ have interfaces and abstract classes as patterns as well.
Not explicitly, but many people implement them as such.
In the editor. Drag your object somewhere in the assets folder to create a prefab from a scene object.
but that gameobject is being created during the runtime
Same as abstract classes, when you want to avoid the downsides of an abstract class.
how can I drag it, if I dont have it yet?
nvm, I can drag it during runtime and it stays
do you have any technical examples such as in games
Don't you have it somewhere with all the references assigned already?
Sure. For example, you can have an IInteractable interface in your game. All the interactable objects would inherit from it and implement it's methods.
ohhhh. like an IDamageable?
Probably these are referencing scene objects. You can't reference scene objects from outside the scene.
For example, yes.
ic thanks
Ok so
Instead of spawning a gameobject
i spawn this prefab
that alr has all the references available
like a prefab with all the inspector made alr
Yes. Assuming it refrences things on the same gameobject or it's children, it should be fine.
What does that mean?
Yes
but its assigned
So I added this
public GameObject Camila2;
GameObject instance = Instantiate(Camila2, new Vector3(1,1,), Quaternion.identity);
And I assigned it with the prefab that I dragged
in the assets
its the same problem
the exact same problem
The prefab its not assigned in the inspector cause that gameobject it was created inside of the script and the inspector is empty
Is it not empty in the prefab?
can someone explain to me (in the easiest way possible) what a static variable is ?
A static variable is a variable which can be accessed using the class name rather than an instance of a class
oh so when you need to access that variable you need to use the specific class, without even declaring it in another script ?
because of this there can only be one value for a static variable regardless of the number of instances that the class may have
yes
i am trying to learn data persistence between scenes and i want to fully understand it
Static variables are not a good way to persist your data. They are just easy to access because they don't need an instance
static varialbe values will persist
If you want to persist data, consider storing gameobjects using Dont Destroy on Load, or create a separate transient scene that always exists
Using static variables when their gameobject has already been destroyed can lead to messy code
It is a tutorial from unitylearn
And on the topic of static and persisting data, your gameobject could be turned into a singleton if you are storing data in it. The singleton pattern is perhaps something you could take a look at how they work.
Oh, you already have a singleton instance here 😎
that's the script from the gameobject that I want to save between scenes
Alright, all you need to do is call Dont Destroy on Load on it
This creates a new scene managed by Unity where all objects must exist that don't get destroyed
and the "this" variable is basically what am i assigning the script to ?
this means the calling class, so your MainManager instance
alright
You assign it to the Instance field, which is static so you can easily get this instance again
yeah
Your code in Awake basically checks for an existing instance in Instance, and if so it destroys the second instance of MainManager, since we already have one
Sorry, I misread your code. You already call Dont Destroy on Load
You don't need to do anything in that case, this object already persists
I understood that part, because if I don't have that if statement it keeps creating more MainManager gameobjects
yes, the code works , but I wanted to go into deeper explanations so I can fully understand it
So what do you want to know?
so the "DontDestroyOnLoad()" method creates that separate scene that saves my gameobject, right ?
Yes, if you start up your game and make a manager instance you can see the scene in your hierarchy
Yes
You can also make a second transient scene and do it yourself
This is mostly useful if the first scene varies or you don't want to be bound to one
I will do so
This line of code loads Json files from a subfolder of my Resources folder. It works in the editor but I'm not able to retrieve them in WebGL builds. Do I need to switch to a StreamingAssets approach to access json files in this way in WebGL?
currentNode.nextDialogueJsonFile = Resources.Load<TextAsset>(currentNode.nextDialogueJson.Replace("Assets/Resources/", "").Replace(".json", ""));
If that works in Editor it should work in WebGL. What errors are you getting in the web developer console of your browser?
You know what, I actually just made a clean build to test it again and it might have to do with how I'm tracking the dialogues themselves. I'm going to look into it a little more before I come back.
so i am trying to make a movement system, and my gravity isn't working, it keeps adding down force with out resetting it/stopping. pls help am very stupid (its also not giving any errors its just not working as its supossed to)
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2.0f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
velocity.y -= gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}```
what is the point of this
if(isGrounded && velocity.y < 0)
{
velocity.y = -2.0f;
}
when 5 lines later you do this
velocity.y -= gravity * Time.deltaTime;
{
velocity.y = -2.0f;
} ```
is supossed
tio
reset
velocity
write in full sentences
sorry, it was bc i pressed enter without holding shift for new line.
but basicly if(isGrounded && velocity.y < 0) { velocity.y = -2.0f; }
is my attempt at reset the velocity, and velocity.y -= gravity * Time.deltaTime; is supposed to give you more velocity as ur falling to make it more realistic
so you logic should be
if grounded
velocity.y = 0
else
velocity.y = apply gravity
why did i not think of that 😭 lemme try doing smth like that 2 sec
i think this will work lemme try it
i might be wrong
so before for moving object along linerenderer i was calculating length of each segment and adding them all together, but when i will start generating curves it may be getting laggy jumping through all segments every frame, i thought to instead make very large array of positions where distance between each of them is exactly same, so then i can get position directly with [i] is that good or bad
Wait oops i ment ``` if(isGrounded)
{
velocity.y = 0;
}
else
{
controller.Move(velocity * Time.deltaTime);
}
but i just tried that, it didnt work, its still just added velocity
I see no gravity there
You don't need any of it. Line Renderer already contains list of all its nodes. If you want to move something along it length just pick a step, if you get to a corner and step has a remainder movement, move by that amount to the next node.
if(isGrounded)
{
velocity.y = 0;
}
else
{
controller.Move(velocity * gravity * Time.deltaTime);
}``` i just tried this, that didnt work
i dont think i am understanding what ur saying
look at what you already had
velocity.y -= gravity * Time.deltaTime;
yes im saying if theres like few hundred points i have to calculate all these steps each frame
ohhhhhhh wait
ok
2 sec
So what are you asking then? Obviously if you want to move along something, you have to calculate it.
If you want to skip the manual calculation, you can use the Spline package and just sample it based on how far you want the object to be along it.
I have no idea what you are doing or what you are trying to achieve but, you mentioned yesterday having 1,000 line renderers with 1,000's of points each. This strikes me as a serious design mistake
that why i thought of making big array with excessive points but distance between them is same
{
velocity.y = 0;
}
else
{
velocity.y -= gravity * Time.deltaTime;
}``` is this what u meant?
so i dont need care about poitns only length of array
Sounds silly, but it's you so doesn't surprise me. Good luck.
And the Controller.Move?
{
velocity.y = 0;
}
else
{
controller.Move(velocity.y -= gravity * Time.deltaTime);``` sooo like this?
no, you need both
{
velocity.y = 0;
}
else
{
controller.Move(velocity * Time.deltaTime);
velocity.y -= gravity * Time.deltaTime;
} ``` so this?
i would to if i were u
Honestly, does that code make sense to you?
like kinda, i was half following a tutorial by brackeys and half trying on my own.
Tell me then, what is the point of using velocity BEFORE you have set it's y property?
and why would you use deltatime twice
i thought real hard about this for five minutes and i couldn't come up with an answer (he didnt really say anything in the video about it, and i cant tell if this is a sarcastic question)
i was just copy and pasting different lines together
Hello, guys! Could you please tell me the most efficient and simple way to create stairs functionality for my player in a first person horror game? I want to learn the methodology of that functionality.
I was working on animations when all of sudden the animator blocks disappeared and it starts giving me this bug
why?
if your character is using a character controller you just need to tweek the "Step offset" thing in the character controllers propertys
I don't use that, I am using rigidbody.
I think I have to make that thing with raycast right?
stepLower and stepUpper
That's all very confusing really
i cant help you then i am not good at scripting
You have a missing component on an object
Oh, it has to do with state machines I dont know that I thought it was the common one
I don't know either all of sudden it happened i think i should close and open unity probabily an engine bug
Close the Animator window and restart the editor
it looks like something went wrong in the graph view
Did
And the issue persists?
No, it worked
