#💻┃code-beginner
1 messages · Page 174 of 1
it no no works :(
Of course, because of the issue I presented in the very same sentence
Warnings are there for a reason!
It requires an extremely precise timing for it to work. Once the coroutine resumes you have around 16 milliseconds (assuming 60 FPS) to press the key. Too fast, and the coroutine hasn't resumed yet. Too slow, and the coroutine ended already.
but then it's veryhard to code?
i do not understand that warning
right?
Very hard to code? What
oh wait nvm
Click the cookie texture in the Project browser. The inspector will show import settings for that texture
Change Wrap Mode to Clamp, then hit apply
do i need to make it inside so i will be a part of the if?
Why is there a delay? Is it supposed to be a cooldown for the shooting?
1800 canon have a delay
of abt 1.25 sec
1800's
I see
Just having WaitForSeconds does not prevent other Shoot coroutines from starting
You could use a bool like isCoolingDown that you set to true when shooting. Set it to false after the Wait
And don't start a new Shoot coroutine if that bool is true
Yeah, and you'd want to do this in the right order
KeyDown -> WAIT -> Shoot
Also the KeyCode.F check would make more sense in update
Ohh right, it's a pre-delay
Like, the fuse
Your code had KeyDown -> Shoot -> Wait
And putting it before the if would do Wait -> KeyDown -> Shoot
hold on i wont be responing gotta do smth real quick
Filtering for triggers and anything else that "collects" gameobjects.
{
// Start is called before the first frame update
public Vector3 scaleChange;
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.localScale. += scaleChange;
}
}```
why does this not work, im a complete beginner following the tutorials
whats value of scaleChange in inspector ?
it says identifier excepcted
Fix your IDE
i did
uh which .
shiteee
Hi, is it possible to get the value of a variable from Script A and use it in Script B? I tried it this way
I wrote this in script A
public bool IsGrounded()
{
return m_Grounded;
}
And this in in Script B
public FoxController2D foxController;
if(foxController != null)
{
grounded = foxController.IsGrounded();
}
And what's the issue? It seems odd you're checking for null, do you expect that value to ever be null?
so can i make a coroutine false?
no
dang it
they saying put a bool check before starting one
The problem is that I need this variable which gets processed in another script to be transfered to the other script. And I just don´t know how to do it, checking for null was an advice from chatgpt
They're asking about what's the issue with your current code? Does it not work?
checking for null was an advice from chatgpt
not a good way to learn
no just no
i tried using it
but no
worst idea you could have thinking about
it doesn´t work
chat gpt is 💩 in coding
well, it wouldn't do anything or error if it was null
remove the null check
and then make sure you check the console for exceptions when the code runs
ok i´ll try it now
Is there a way for a script that is instantiating an object to add itself as a component to that object?
What does "add itself as a component" mean? Actually Adding the component to the other GameObject?
You can't move a component to another object
But you can add a fresh one with AddComponent
It wouldn't be attached to anything, just an instance of a class
"NullReferenceException: Object reference not set to an instance of an object"
You mean, referencing the original component when you instance?
So, now you know that foxController is null. Assign it a value
why is touch.position set to several hundred thousand? when an item is not held, the position is calculated and placed normally, this is only for the drag visualization code
could i do it like this?
if (foxController = null)
{
variable = 0
}
Where do you assign a value to foxController
in another script
In the script that is throwing the error, where do you assign a value to the variable foxController
These two screenshots were taken while the object was being held, and the positions should be identical.
in void Update()
Show the code where you assign a value to foxController
Are any of the parents of the item offset by a large position?
Have you tried initializing a script variable that you can then assign the variable to?
i have a question it might be super stupid for you guys, you know how we use update, wouldnt that mean if somebody has a better pc with more fps the gamer would make some things faster than intended?
the parent is a canvas set to screen space camera, so it doesn't have an offset
- !code
- Where do you assign
foxController
📃 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 (scriptname) script;
yes that's the entire point of deltaTime
Yes. That's why there's a concept of framerate dependency/independency.
What is delta time
scratch that, the parent is a sprite on said canvas, posX 110 and Y 2110
deltaTime is the time since the last frame
i dont understand, woukldnt the time since the last frame also vary based on pcs
well, that would contribute to a slight difference in the local position, however it doesn't explain what you've got there. Something else must be positioning it, or the positions you logged are not actually what's being set
That's the whole point, yes. Read the documentation
you would multiply something by deltaTime IF you want it to be the same for all computers
You can see the log code and the position setting code here
Or a blog, or any of the thousands of resources that explain it
a person would 1000 fps would run faster than a person with 10 fps, you can use deltaTime to make them go the same
how does that work tho i dont get the logic
i posted it
Well, the time since last frame is basically the same on all computers
wouldnt it be faster if the pc is better
Follow the instructions on how to post the code properly, and show where you assign foxController, which was not in that code
Use the specified links to post large codeblocks, as the bot says.
For example you move an object some amount * delta time every frame. At higher fps, it would move less every frame. At lower fps, it would move more every frame.
Because if every frame they run at 1 * Time.deltaTime units, the guy who gets 1000FPS will move 0.001 units per frame and the guy getting 10 units per frame will move at 0.1 units per frame
ohhhhhh
yeahh i get you since the better computer would have say 2k fps and the time would be 0.001 it would make the time ahhhhhh thats so smart
!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 hope I did it right now
where is it
What do you mean?
Where is the link to the code
Where do i get the likt to the code?
from the address bar
Go to one of the sites, paste in your code, click save, copy the URL
oh ok i`ve never used this service before
https://gdl.space/apusatecez.cpp
Is this the code throwing the error
This code doesn't explain how you assign a value to the foxController variable
im gonna dream about time delta time today gn 
Okay so where in this code do you assign a value to foxController
Where do you tell this code which FoxController2D that variable holds
And as I linked before, this is how you should be doing it with your current code, and if it's null then you've failed one of these steps: https://unity.huh.how/references/serializing-component-references
Also, why do you have two variables, controller and foxController?
tbh i asked chatgpt how to get one value from one script to the other one and that`s how it told me how to do it by defining public FoxController2D foxController
So instead of listening to the spambot, you should look up actual resources. Ones that know things
stop mentioning the robot that autocompletes text
You aren't going to get very far by doing a fancy version of typing the word public and hitting the middle option on your phone keyboard until the program is finished
The instantiation part works, but the created object has neither a LineRenderer nor an EdgeCollider
Instantiate(m);
ec = m.AddComponent<EdgeCollider2D>();
lr = m.AddComponent<LineRenderer>();```
Instantiate returns a reference to the newly spawned object
thats why i am here in the code-beginner section, because until now i didn`t program and startet yesterday
So this should work?
m = Instantiate(Resources.Load("Vessel") as GameObject);
You should probably just make whatever "Vessel" is already have those components on it
Sure
So you should probably read the resources you've been linked to and try learning on your own
sorry for wasting your time
The debug.log claims that the selected item's position is correct but the inspector shows it a hundred thousand units away and displaced by 1520 in the Z axis, the hierarchy is also visible in the editor screenshot.
The inspector shows local position
relative to the parent
you can see in the inspector the parent hasn't changed, item(clone) is still a parent of grid1
What are the positions of grid1 and canvas
And scales
Sale of canvas is 0.0003 for some reason, but it's screen space camera so I can't alter it?
scale of grid 1 is just 1 1 1
Change your log to this:
Debug.Log($"{rectTransformOfItem.gameObject.name} is at {rectTransformOfItem.position} world, {rectTransformOfItem.localPosition} local", rectTransformOfItem);
It'll give more info, and when you click once on the log it will highlight the object whose positions it printed
Is it parented to anything?
Yep, seems like that's what you're getting. You're setting it to the world position 370, 1673, 0, which translates to that in its parent's reference frame
Try this: Create a cube that is not a child of any object. Set its position to 370, 1673, 0 and compare where it is to the thing you've cloned
That is the position you're telling the object to go to
it's a little off, the white speck is the cube, the widget is the sprite
{
public Transform bulletSpawnPoint;
public GameObject bulletPrefab;
public float bulletSpeed = 100;
private bool IsCoolingDown = false;
public AudioSource CanonShot;
public ParticleSystem CanonMuzzleFlash;
void Update()
{
if(IsCoolingDown == true)
{
StartCoroutine(IsCoolDown());
}
}
void OnTriggerEnter(Collider Player)
{
if (Player.tag == "Player")
{
Debug.Log("canon shot");
StartCoroutine(Shoot());
}
}
IEnumerator Shoot()
{
if (Input.GetKeyDown(KeyCode.F))
{
IsCoolingDown = false;
yield return new WaitForSeconds(1.25f);
CanonShot.Play();
CanonMuzzleFlash.Play();
Vector3 shootD = (bulletSpawnPoint.forward + bulletSpawnPoint.up * 2).normalized;
var bullet = Instantiate(bulletPrefab, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
bullet.GetComponent<Rigidbody>().AddForce(shootD * bulletSpeed, ForceMode.Impulse);
Debug.Log("coroutine executed");
IsCoolingDown = true;
}
}
IEnumerator IsCoolDown()
{
yield return new WaitForSeconds(4f);
}
}``` is good?
needed to zoom out a ton to get both in frame
No https://unity.huh.how/coroutines/waiting IsCooldown is nonsense
What is the point of the IsCoolDown coroutine? It does nothing, waits 4 seconds, then does nothing
Is this perhaps what you want
https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
changed screenshot to include heirarchy
i never understand unity docs
it'salway the same script there is nothing related to the subject
I was hoping the cube would demonstrate what I was trying to convey but I guess my math was off and my example backfired, so I'll just say what I was trying to get at
Your issue is you're using a screen position in pixels as a world position in meters. Your object is way off from where you think it is because the canvas is not an object that physically exists, it's basically a transparent film stuck to the inside of your camera
This all makes complete sense to me. ScreenSpace - Camera is in the space of the camera (a little plane in world-space in front of the camera), and you're spawning something in world-space using Screen space coordinates
there is nothing related to coroutines
This was not in response to you
If you are having this much trouble reading the discord reply chain I can see why you can't read the documentation
srry u sent it directly after u rplied
Yes because I'm talking to multiple people, that's why I reply to them
I read through the doc you sent, and applied it as best I could tell. the new result is still off but in a different way
Attempted a new solution, got much closer to correct. By assigning the touch's position to the itemRectTransform.localPosition, the image is on the same plane as the canvas, but transposed about the screen's height upwards
localPosition will be relative to whatever the item is parented to
!docs
is there an easy way to get it relative to the grandparent, instead?
so this canvas is in Screen Space - Camera mode, correct?
yes
sure -- grab the transform of whatever you want to set your position relative to and then use Transform.TransformPoint to turn a local-space position into a world-space position.
transform.localPosition = pos;
transform.position = transform.parent.TransformPoint(pos);
for example: these two are equivalent statements
It's very small because the canvas's width and height are set to your screen's width and height in pixels.
So to fit the camera in front of your camera at a distance of 5 meters, it must be scaled down a lot
So a local position of, say, [300, 500, 0] translates to a very small amount of movement in world space, because the canvas has been scaled down a ton.
(I say 5 meters because that's the Plane Distance you've chosen)
If that misbehaves, then I'll need to look a lot closer at what you're doing
so to do this, I need to give the canvas directly to the script as a public variable? or is there a way to grab it without that?
if you just want your grandparent, that's transform.parent.parent.
It sounds like you want to set the position of the object in the frame of reference of the canvas, though.
In that case I would either hand the component a reference to the Canvas or use GetComponentInParent<Canvas>() once
var canvas = GetComponentInParent<Canvas>();
transform.position = canvas.transform.TransformPoint(screenSpacePosition);
This would position your object on the plane of the canvas.
for clarification, the script running this code is on the camera, not the objects being moved
TransformPoint computes where in the world a local-space position is from a given Transform's point of view
This takes into account rotation, scale, and position
TransformDirectiononly cares about rotationTransformVectorcares about rotation and scaleTransformPointcares about position, rotation, and scale
remember that the local position of the object will not match the screen position
since its parent is not the canvas
right, so var canvas = selectedItem.GetComponentInParent<Image>().GetComponentInParent<Canvas>(); ?
wait, no
var canvas = selectedItem.parent.GetComponentInParent<Canvas>(); ?
no, I'm telling you that selectedItem's local position should not match the screen position
unless it's parented directly to the canvas
or parented to something that's parented to the canvas and that has zero position, zero rotation, and one scale
see this example.
Okay, I see now. I need to take the position, and subtract the transform of the grid, because currently the grid's transform and the item's are being added together?
What are you trying to actually do here?
I don't know what your hierarchy looks like so I'm a bit in the dark
Item(Clone) is on a grid, and I need it to follow the pointer when it is being moved from one slot to another.
"from one slot to another"?
it's a tarkov/resident evil inventory tetris type thing, the grid is an image with a tiled sprite applied. The actual storage and placing and removing is handled in another script and working fine, with position decided using the grid coordinates of the cell
okay, so you're just trying to make the item stick to the pointer. got it.
exactly, yes
in what way does this code not work correctly?
you showed the console, but that doesn't really tell me if the item is positioned wrongly in the world
the Z position certainly looks right for a camera at the world origin (since the Plane Distance is exactly 5)
currently my finger is on the bottom left cell
when I let go, the item does slot into the correct cell, it's just the floaty preview that is off
is there any harm in just parenting things as a quick-fix rather than scripting
like parenting your camera to the player so it automatically follows it instead of creating a script that makes it follow
im not looking for answers to that specific example i just wanna know the pros and cons of doing so
if you just need X to follow Y, parenting makes plenty of sense
There's no "harm" in it. It does what it does. As long as you understand the consequences go nuts.
Btw you don't have to write anything to have something follow something else. There's built in components like PositionConstraint and ParentConstraint for that
heh yeah i gotta learn the documentation lol
i'm just starting out so the Unity-specific variables and stuff I'm not well-versed in
any super important Unity variables that you think i should know, some that could really help but i might not find out about easily?
there aren't really variables. there are certainly lots of methods that unity calls on MonoBehaviours, though
consult the Messages section
Is it a constant offset?
yknow, the stuff that isnt in basic C#
yes, it follows my motions without any apparent movement scaling. It's just an offset
woah-hoh theres a lot of these
ooh right, I forgot an important thing
the canvas's origin is the center
that's why you're seeing exactly half a screen height and width's offset
oh that scans yeah
hm, what's the smoothest way of doing that correctly..
is there a better fix than just postion.x - screenwidth / 2 ?
it feels janky but it would work
the first thing that comes to mind is that, yeah
the second thing is to use Camera.main.ScreenToWorldPoint
you'd set the Z coordinate of the point to 5
because that's the distance of the canvas from the camera
This should do the trick for you.
Transform a screen space point to a position in world space that is on the plane of the given RectTransform.
Pass it the canvas's RectTransform
This has an out parameter. You can use it like this:
RectTransformUtility.ScreenPointToWorldPointInRectangle(canvasRect, screenPoint, Camera.main, out Vector3 worldPoint);
item.transform.position = worldPoint;
what a mouthful of a name
Good name, explicit is good
quick question, what does the majority of necessary unity code go towards specifically? camera movement? physics simulation?
cause like the scripts im seeing so far seem relatively simple yet they do a lot, player movement is only a couple lines of code, so where does the rest go typically
so set the canvas.rectTransform to canvasRect, and touch.position to screenPoint?
Correct.
can't really answer that question
I guess I could count how many lines of code my project has in various categories
loll no need to do that dont worry its all good
im just curious about the contrast between the beginner scripting courses im taking, and the advanced coding that's at the end of the tunnel
maybe ill find out as i go along anyway
Canvas does not contain a definition for rectTransform
oh, I didn't know if that actually existed :p
just cast the canvas's Transform to a RectTransform
I have 4,600 lines of UI-related code, apparently
this is being very generous, since that's included blank lines
Loll okay fair enough you could probably halve it at the least
still, you must be making quite a big game to need that many UI lines
You are a lifesaver
I built a pretty elaborate system, so there are a lot of scripts in there
Games do a lot of things.
I have a lot of code for really boring stuff, like saving and loading your settings reliably
ahh so is it more like, behind the scenes work rather than direct game inputs
is that where the bulk of the code goes
my VSC seems to hate me and want to block all of my progress. Is there a reason why like 50% of the time I try to code it just refuses to understand what code in general is? Like why the hell is the if statement an error. If I put this stuff into a different class it works perfectly fine, it just seems to randomly hate certain class files for NO reason
do you have a class and a method
Do ya not need a namespace?
yeah wheres the namespace
my bad prolly shoud've shown the entire class as well
without the error message hovering over it
Oh yeah
no, you dont need a namespace
Start, update, something?
Ah mb
you can't just write code outside of a method
Your code right now isnt inside any function, there is nowhere for this to run. You should do some basics of c# first
that's not valid C#
no you're right I did need an update function. im a complete idiot
no, I understand the basics I'm just entirely idiotic sometimes
oh i was right! first person helped by me less go
Good night. I'm a beginner in programming, and I'm trying to make a simple game of choices, for example:
"You are walking in the forest and you find two paths, the one on the right and the one on the left. Which one do you choose? 1 . right or 2. left"
I'm trying to do this with buttons and text box, then when I choose 1 it gives me one answer and 2 another. But I want to do a second part with choice and it's not working.
note: I asked chatGPT for help to do 90% of the code, since I'm still learning, and it has already given me a lot of code.
Can anyone help me?
!code but you likely arent gonna get help with gpt code in the first place
📃 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.
that's going to give you a gigantic pile of AI-generated sludge that's basically unmaintainable
i would strongly advise looking up tutorials for text-based games
Do you need to use a case? And can you use cases in unity now that I think about it?
i was using if else
Any reason you are using Unity for this?
no
hello im a beginner in c# is there a good playlist or something i follow to learn it?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks man
C# console can do a text based game pretty easily, or are you wanting visuals? (I'm assuming ya want on click, return variable if unity is being used mostly for the visual
visual
If you want to make a text adventure it would be easiest to do that as a commandline app
yes
And ya found put how to make buttons?
There should be some pretty good video tutorials on how to make functional in game buttons
Ooh, a text based rpg?
yes
Looks pretty nice
thx
dope
yes
And +/- ig
quest, inventory and map
I don't understand, sorry
im from brazil
google tradutor is my savior
Ouch, I was gonna recommend a video lol
How to create buttons in Unity? Let's have a look. We will create and script buttons in this Unity tutorial for beginners.
····················································································
♥ Subscribe to Oxmond Tutorials:
https://bit.ly/SubscribeOxmondTutorials
● Get the FurBall character from the Unity Asset Store:
https:...
Not sure if it will help since it's in English but it should give a walk through
Usually no video shows exactly what I'm looking for
Probably the case, but if you can get a button to show a debug log when ya click it, ya can pretty well make it do anything else after
If getting the click input is your issue
My button is already following the story normally, but in the part of making the choice, it gets lost in the index and doesn't follow the story
if you can translate the errors
Question text isn't changing
is it unity only?
That's not to bad, ya need some variables to set which text shows
i know no c#
dialogueIndex 12 is not immediately after a known choice point.
UnityEngine.Debug:LogError (object)
there is some points of choice
private readonly List<int> choicePoints = new List<int>{12, 14};
yeah so index error
index 12 is a point
the text is in the index 12
dialogueIndex: 12
UnityEngine.Debug:Log (object)
choicePoints: 12, 14
UnityEngine.Debug:Log (object)
there are many basic c# tutorials online, this is a unity discord though.
you're accessing an index of 12 probably with 2 indices
I don't get it
is it better to learn basic c# first
you define 2 indicies, 12 and 14, but you're accessing the list as choicePoints[12] probably which is out of bounds
that's the only thing I can think the error means
otherwise need to see code
private void SetupChoiceButtons()
{
Debug.Log("Configurando botões de escolha...");
foreach (var button in choiceButtons)
{
button.onClick.RemoveAllListeners();
}
if (dialogueIndex == choicePoints[0])
{
choiceButtons[0].GetComponentInChildren<TextMeshProUGUI>().text = "Usar a pedra";
choiceButtons[0].onClick.AddListener(() => OnChoiceMade(1));
choiceButtons[1].GetComponentInChildren<TextMeshProUGUI>().text = "Usar a vara";
choiceButtons[1].onClick.AddListener(() => OnChoiceMade(2));
}
else if (dialogueIndex == choicePoints[1])
{
choiceButtons[0].GetComponentInChildren<TextMeshProUGUI>().text = "Espada e escudo";
choiceButtons[0].onClick.AddListener(() => OnChoiceMade(1));
choiceButtons[1].GetComponentInChildren<TextMeshProUGUI>().text = "Arco e flecha";
choiceButtons[1].onClick.AddListener(() => OnChoiceMade(2));
choiceButtons[2].GetComponentInChildren<TextMeshProUGUI>().text = "Cajado e tomo";
choiceButtons[2].onClick.AddListener(() => OnChoiceMade(3));
}
for (int i = 0; i < choiceButtons.Length; i++)
{
choiceButtons[i].gameObject.SetActive(dialogueIndex == choicePoints[0]? i < 2 : i < 3);
}
}
opss
ok, so index 0 and 1 should work, right? But you have no choiceButtons[2]
yes, if you want to learn properly and have the patience to wait to start game dev. We see people trying to learn c# and unity at the same time everyday. It is like trying to do advanced physics while not knowing what 1+1 is. They struggle way more than they should
ok 
do yk any good basic c# channels tho?
yeah, this is basic indexing stuff which can be simply an afternoon to learn instead of relying on chat gpt
This part is the closest I've come to figuring out the error
give me the line specifically
sorry, i dont look at any myself so cant really suggest there. i think w3schools is a decent start but it doesnt cover the real technical side of c#. Jamie king has a few good in depth c# videos but i forgot how advanced it is. He does explain clearly though
Some of its outdated too😅
ok np thanks for the info tho
I messed up by using only w3 lol
coding doesnt really change, so i dont know what u mean outdated
i have this part that i was using before switch case
Honestly this is where breakpoints shine when it comes to debugging, but you can do it the old fashion way and just throw debug.logs everywhere and name them orderly
i made this
but didnt help so well
This part was the closest I got because of debug.log
choicePoints[1] + 1)```
Start sharing the code properly please.
!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.
GameObject pieceToTake = new GameObject();
pieceToTake = GetComponent<GameManager>().tilePrefab.transform.GetChild(0).gameObject;
pieceToTake.GetComponent<PieceManager>().SetPieceType(hit.collider.transform.GetChild(0).GetComponent<PieceManager>().GetPieceType());
I run this each time I click the mouse button, I then add the pieceToTake into a list.
When I click though, all objects in the list get effected by line 3 anyway
How do I make it so each pieceToTake object is a seperate object?
this is the second choice of the history
the first one is [0]
Wouldn't cs choicePoints[0] + 1) be the second?
if (dialogueIndex == choicePoints[0] + 1)
{ .......
else if (dialogueIndex == choicePoints[1] + 1)
{
first part is [0]
second part of the history is [1]
history or story?
this code doesnt really make sense, you create an empty GO then immediately try to GetComponent<GameManager>. There is no GameManager on this object, this should result in an error
That may be part of the problem ngl
this object has a GameManager component with a prefab reference, I'm just trying to set the new game object to a new instant of that prefab
based on your code, it literally cannot have a GameManager component at that time
GameObject pieceToTake = new GameObject();
pieceToTake = this.GetComponent<GameManager>().tilePrefab.transform.GetChild(0).gameObject;
pieceToTake.GetComponent<PieceManager>().SetPieceType(hit.collider.transform.GetChild(0).GetComponent<PieceManager>().GetPieceType());
oh
The expression dialogueIndex == choicePoints[0] + 1 is used to check if the current dialogue index (dialogueIndex) is exactly one point after the first choice point recorded in the choicePoints list.
Here's what each part means:
-
dialogueIndex: This variable represents the current index in the dialogue flow. You can think of it as the current position in the narrative or conversation being displayed to the player. -
choicePoints: This is a list that contains the indices of dialogues where the player needs to make a choice. Each element in thechoicePointslist represents a point in the narrative where the flow can change based on the player's choice. -
choicePoints[0]: This expression accesses the first element (or first choice point) in thechoicePointslist. Since the index of an array or list starts from 0,choicePoints[0]is the first choice point added to the list. -
+ 1: Adding 1 to the value ofchoicePoints[0]means we are referring to the index immediately after the first choice point.
Therefore, the comparison dialogueIndex == choicePoints[0] + 1 is used to check if the current dialogue is the moment right after the player has made a choice at the first decision point. This is useful for determining when to insert the consequences of a choice or to continue the narrative in a specific way based on the choice made earlier.
This logic allows the game to respond to the player's actions by adjusting the dialogue or narrative based on the choices made, ensuring that the following dialogue or events are relevant to the decision made by the player at the choice point.
+ 1: Adding 1 to the value of choicePoints[0] means we are referring to the index immediately after the first choice point.
i misread where the GetComponent was called sorry. But your code right now is actually creating a new empty gameobject in your scene and then not using it. you can skip the new GameObject(); part
Okay, I think a better way of wording it is how can i add pieceToTake to my list by reference instead of value.
based on what you described initially, it sounds like you are affecting some value on a prefab
GetComponent<GameManager>().takenBlackPieces.Add(pieceToTake);
this is right now
but when i do
pieceToTake.GetComponent<PieceManager>().SetPieceType(hit.collider.transform.GetChild(0).GetComponent<PieceManager>().GetPieceType());
it changes every object in the list
this is gpt isnt it...
yes
yea dont paste gpt text. if you cant describe it yourself then step away from what you're currently doing and go learn properly
no one wants to talk to someone, so they can talk to gpt, so it can talk to you, and you can paste it back
I'm saying I've been using chat GPT for a while now
yes i said initially that you likely arent gonna get help for gpt
Start debugging more with logs if that's not the issue.
you'll figure it out yourself instead of asking
What is changing exactly? What value
Honestly running a debug at each task should help
I just tested it and it's not
You tested gtp?
i have like, 11 debug.logs
I put dubugs on anything that I'm testing ngl
whats is ngl?
(Everything if I'm being honest)
Not going to lie
Hey yall, can anyone help me with some networking shenanigains
sorted it with whatever this is
GameObject pieceToTake = hit.transform.GetChild(0).gameObject.CloneViaFakeSerialization();
works now though so :/
Im having some problems with ownership, #archived-networking
🤔 i got no clue where you even found this method, did you use AI?
Either way this probably should not be your solution
seems like thats a method under visual scripting
i was just using intellisense and found cloning, but this is the only one that worked
pretty sure this was your issue #💻┃code-beginner message
because in your initial code you directly used something named tilePrefab
its better when you show more context, its easier to help when i know what values actually are.
you definitely shouldnt use a random method if you arent sure about what it does. try and figure out what the actual issue is
I had tried a load of different things before that too: just an empty game object, obviously had no PieceManager. A piece manager directly, but didn't have Mesh renderer required by it etc, any way i tired before, i either got all objects in my list changing when adding one, or object reference not set to an instance of object (refering to mesh renderer)
🤷♂️ this is all too vague tbh for me to even say more. What is changing specifically? i still dont even know what value you are referring to. And that last thing you mentioned is just a null error, something is null when it shouldnt be.
is there a way to check if a rigidBody.MovePosition will bump something along the path? Rather than physicscast?
isn't that like a straight line of movement
raycast seems like the best idea there
or physicscast like you said
my colider is weirdly shaped 🥹
lemitry\
or maybe it resizes the collider in the direction
no clue on its implementation, but it behaves like spherecast
2d?
Wdym you don't have it?
What's .Cast?
17 🥹
No it's because you're using 2D physics
I thought you were asking about 3D. You didn't mention which
how to make black box not trigger both of red and yellow's OnColliderEnter2D when it goes up?
like just choose one (preferably if it can smartly select the better (more visually overlapped))
layers
if(hasBeenhit) return;
you can set collision matrix, or use layer overrides
using layers is the super efficient way if you have a fuckload of irrelevant collisions, because this will automatically filter out collisions that aren’t supposed to be relevant
because if two layers don’t interact, their objects do not generate OnCollisionEnter/etc when they overlap
i want either, just not both
Guys, my game view doesn't lock my cursor or makes it invisible when in maximized mode. I've had this problem for like 2 days already. It wokrs on Focused just fine
this is what im doing, but doing that for each objects my player can interact is quite dirty+/ repetitive 🥹
It also feels completely arbitrary when it works or not. Sometimes it randomly works, the other day it doesn't
It happens to every new BiRP game I make
i meant store that on player and check it from the box, if already has hit then dont process whatever u have in OnCollision
hmm... like the player holds the query?
But there's a snowball's chance in hell the problem is with the RP (obviously). Is there something worng with my editor? i'm using 2022.3.19f1
that's actually a good idea
My script also looks fine
what's rp? render pipeline?
Yes
RP isn't responsible for the lock state of the cursor
I think it's somethig with my editor
the cursor doesnt lock even if you click the game screen?
I can provide with code if it's of any help but I doubt it's a problem with my script
Yes
It only works on Focused
For some reason
Maximized? not so much
what's Focused?
I Logged both the lockedState and visibility of the cursor and it says it looks good but the scene says otherwise
me is dont have that 
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
The movement code
And:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerLook : MonoBehaviour
{
[SerializeField] private float sensX = 100f;
[SerializeField] private float sensY = 100f;
[SerializeField] Transform cam = null;
[SerializeField] Transform orientation = null;
float mouseX;
float mouseY;
float multiplier = 0.01f;
float xRotation;
float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
Debug.Log(Cursor.lockState);
Debug.Log(Cursor.visible);
mouseX = Input.GetAxisRaw("Mouse X");
mouseY = Input.GetAxisRaw("Mouse Y");
yRotation += mouseX * sensX * multiplier;
xRotation -= mouseY * sensY * multiplier;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
orientation.transform.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCamera : MonoBehaviour
{
[SerializeField] Transform cameraPosition = null;
void Update()
{
transform.position = cameraPosition.position;
}
}
Both camera-responsible scripts
Again tho, I don't think the problem has anything to do with the scripts
It allows you to play your game while looking at the editor?
It's very useful for debugging
You can see what happens behind the scenes
or you know..put the gameview side by side of scene view 
Why do that when you have focused mode
I mean, play it while in focused mode, then only then youll do the rightclick then max
i come from unity when it didnt have it I'm used to it
the GAME word
Nothing shows up
Not that I know of
I think it's a problem on Unity's end
Something with the Editor or smth
I can maybe port it to 2019
I'm more used to it anyway
I just wanted to try 2022
GameObject addedHolder = Instantiate(holder, holderPosition, holder.transform.rotation, transform);
int removeIndex = addedHolder.name.IndexOf("(");
int toRemove = addedHolder.name.Length - removeIndex;
addedHolder.name.Remove(removeIndex, toRemove);//instantiating objects appends "(Clone)" to name, I don't like that here.
addedHolder.name += $" ({j+1},{i+1})";```
am I using `String.Remove` wrong? Nothing is being removed from `addedHolder`'s name
Yes
The String.Remove method does not modify the original string but instead returns a new string with the specified characters removed
Give me a second
strings are immutable
Oh alright
not a (Clone) in sight
You can simply do
gameObject.name = gameObject.name.Replace("(Clone)", "");
anyways, if gameobject names affects you game, you doing something wrong
it doesnt, just makes debugging more annoying
i mean, their purpose is to make debugging easier though
I know, and removing the (Clone) makes debugging easier
easy to figure out who is fking something
var instance = Instantiate(source);
instance.name = source.name;
they're already renamed to have relative subcoords
I wish you could turn off the Clone stuff 😄
that better
yeah have a bool Clone???? in the instantiate
I dont hate the (Clone).. though, I hate those numbers that appear when you duplicate something in editor
Clone is useful sometimes but when you're instantiating a prefab theres not really any purpose
What's wrong with them?
you can change that
just wrote a whole script that worked second try
can off that?
twas quite basic but stilll schocked I didn't add a comically stupid error halfway throughj
Online chess game
they ugly
nah just () to . or _ 
Ugly but necesssary
Not worth changing some mumbo jumbo just to get rid of numbers on Instances
private void FixedUpdate()
{
m_Rigidbody2D.velocityX = moveAmount.x * m_Speed;
animator.SetFloat("Speed", Mathf.Abs(currentSpeed.x * m_Speed));
if (Mathf.Abs(currentSpeed.x * m_Speed) > 0)
{
Footsteps.enabled = true;
}
else { Footsteps.enabled = false; }
}
public void Move1(InputAction.CallbackContext ctx)
{
Vector2 inputVector = ctx.ReadValue<Vector2>();
moveAmount = ctx.ReadValue<Vector2>();
currentSpeed = ctx.ReadValue<Vector2>();
float currentspeed1 = currentSpeed.x;
animator.SetFloat("Speed", Mathf.Abs(currentspeed1));
if (currentspeed1 > 0 && !m_FacingRight)
{
Flip();
}
else if (currentspeed1 < 0 && m_FacingRight)
{
Flip();
}
}
thats my code for movement any idea why the player is like blurry ish when they move
the gif doesnt show it all that good
if i instantiate 2 of the same objects that have the same script if one bool changes on one object will it change on the other
Is the bool marked with the static keyword ?
no why
Then it will not. Generally every instance of a object keeps its own variables that cane be different. The exception are static variables that are shared between instances.
ok what about if the 1st object was instantiated froma prefab then the clone was instantiated from the other one with instantiate(gameObject) would it share it then
it spawns whatever default was in script initializer of field
script is a text file (so i wont name the class as XXScript)
instead when you drag the script of the object it creates a component (ie an instance in main memory)
when you copy the object the new component is initialized by field initializer/awake/start/other stuffs
Actually his question got me reading a bit. I believe that Instantiate will copy over the stste of the bool from the first instance along with any other serialisable fields. If the component does not init the bool by itself in start awake etc it will share the state of the other instance
Or so I think…. In 15 years of doing unity I dont believe I have used Instsntiate on already existing clones…
that's quite interesting actually, I'm going to give that a try. Always assumed a clone of a clone would not share the state
My theory is that it does this for the prefab, it does do a deep copy. So why not do it for the instance
thats cool
did you save script changes during play mode?
This is however my current assumption someone needs to test this
Unless unity saved when It crashed my system
no
hmm check all your prefabs or scene object, some script is erroring
I only have one script
thats the only thing the console gives me
using System.Collections.Generic;
using UnityEngine;
public class gridManager : MonoBehaviour
{
public Sprite sprite;
public float [,] grid;
public int columns, rows, vertical, horizontal;
// Start is called before the first frame update
void Start()
{
vertical = (int)Camera.main.orthographicSize;
horizontal = vertical * Screen.width / Screen.height;
columns = horizontal * 2;
rows = vertical * 2;
grid = new float[columns, rows];
for (int i = 0; i < columns; i++)
{
for (int j = 0; j < rows; j++)
{
grid[i,j] = Random.Range(0.0f, 1.0f);
spawnTile(i, j, grid[i,j]);
}
}
}
private void spawnTile(int x, int y, float value)
{
GameObject g = new GameObject("X:"+x+" Y:"+y);
g.transform.position = new Vector3(x -(horizontal - 0.5f), y -(vertical - 0.5f));
var s = g.AddComponent<SpriteRenderer>();
s.sprite = sprite;
s.color = new Color(value, value, value);
}
}
Oh
huh
I see the issue
I replaced vertical and horizontal with numbers for rows and columns
1920*1080>10^3*10^3=10^6 gameobjects
but not transform.position
shhhh, performance is secondary lmao
it was originally 5x that
which ate my whole 32gb ram
Ooh thanks, Ill save that
Yes it does! you're right on that
just tested it
if Instantiate uses the modified clone and not prefab it copes its values not uses the Initializers
That might be the reason I have been avoiding it 🤣
Yeah I never actually cloned a spawned prefab before , but yeah it does copies values apparently, interesting TIL
Well this deep copy mechanism is the reason Instantiate is considered slow. It does it for prefabs but there really isnt a reason for it not to do it for anything it clones
Wont be much of a “clone” really
double edge sword, on the other hand is kinda handy knowing it can deep copy like that
Obviously a private field is not serialised in the first place
yes, depend if the fields can be serialized to read the value
Nor can Instantiate get to it in any way
Thats why I said serializable fields in my initial assumption
If you have a custom Type that is not serializable it wont get copied as well
this in action
Should only be filling the camera with a grid of squared
https://docs.unity3d.com/ScriptReference/Screen-width.html
The current width of the screen window in pixels (Read Only).
you cant simply use some coordinate in screen space in your world space
Hey! Quick question, how could I make a charactercontroller get a quick burst of speed that kind of de-accelerates really fast?
I want to have a type of jump where you get a lot of sideways momentum depending on which way you start jumping
1281
mb, just following a tutorial
Detect input that you are dashing, add some big dash velocity to your existing velocity. Handle some sort of drag to slow down.
I have this so far, but its a constant speed increase
u tellin this to me?
Yes
okay
how could I add a drag then
I tried and it always ended up being weird
i tried using a lerp function i think
Well the simplest drag is just a force acting in the opposite direction of your movement
well that would mess up the charactercontroller movement
Why would it ?
if I tried having multiple Move() calls happen in update
it'd make it jitter
one tells it to go left
another tells it to go right
Sure just use one move call
Add and subtract to the same velocity vector
And at the end tell the cc to move with it
this is kinda what I have btw
Thy to refactor your code to have a single move it will make it much easier to add things then
it already only has a single Move() going at the same time no?
The CC just wants a vector to move in. Everything like input gravity dash air friction pushback from a explosion can be stuck into that one single vector
well technically there's vertical and horizontal being different
At the same time sure. Im talking about a single Move that happens right at the end of your Update
just requires formulas i suppose yeah
ah, I get what you mean
but how can I add like the horizontal and vertical movement together then?
just a +?
Yep
Well a good idea is to add up your input vectors, normalize it and then apply it to the velocity by some move speed
here I come ig
i get what you mean yeah
i did this but it looks hella unclean
I probably want some formulas
I can also probably add these up to be like half the length
Just add them up in a variable before hand ?
You also dont need the else gravity
I mean you do want it but you can offload that logic before
I added that because I want gravity to function even when the player has the canMove turned off
but yeah I get what u mean
this should work better right @charred spoke
Vector3 horMoveDirection = transform.rotation * new Vector3(Input.GetAxisRaw("Horizontal"), 0f, 0f).normalized * Time.deltaTime * vertSpeed;
Vector3 vertMoveDirection = transform.rotation * new Vector3(0f, 0f, Input.GetAxis("Vertical")).normalized * Time.deltaTime * horSpeed;
_controller.Move(horMoveDirection + vertMoveDirection + _gravPull * Time.deltaTime);```
tho i might want to initialize the vectors in the file
not every update
Again im telling you to sum up everything inside a single Velocity variable and pass that onto the move
sure
It should work exactly the same as before, its just going to be easier for you to add changes to the velocity
ah right I get it
is it okay to have that Vector3 HorMoveDirection in update?
shouldn't I initialize it in the header?
Its perfectly fine
Putting small structs like a Vector3 on the stack is not a perf issue
Very very new to Unity so apologies if my terminology is incorrect but in a script I'm trying to access the "Speed" part of the Surface Effector 2D Component so I can tune it with Keybinds, but I'm not exactly sure how since it's in the drop down menu of "Force". According to both VS Code and Unity the Surface Effector 2D doesn't contain the definition "Speed". Here's what I tried:
SurfaceEffector2D.Speed(slowedSpeed);```
And:
```float slowedSpeed = Input.GetAxisRaw ("Vertical") * slowSpeed *Time.deltaTime;
SurfaceEffector2D.Force.Speed(slowedSpeed);```
https://docs.unity3d.com/ScriptReference/SurfaceEffector2D-speed.html speed lowercase and it's a field, not a method
also you need an instance of the component with GetComponent for example
and I doubt the speed should be multiplied by deltaTime
Oh yeah now that I think about it, deltaTime doesn't seem needed in this case. I'll do some research on how to GetComponent. Thank you so much!
hey guys, im getting a weird error saying that "combined mesh" doesn't have read/write enabled, heres the thing:
the mesh that im trying to read data from, is a probuilder mesh on a game object named Cube, as you can see in the console;
and when i open the pro builder mesh in the inspector, it says it has read/write enabled.
so what's the issue?
ive had 3 other pro builder meshes give me the same error, but all the other probuilder meshes, and normal mesh renderers are fine
code reading the mesh : https://hastebin.skyra.pw/lihesicolo.csharp
where HandleImpact() is called, and the error /\
When trying out a new retro-style for my game this returnss for some reason
I can move around and do other things an the camera clearly works
But it still returns this
I'm using a custom raw image texture for the pixelation effect
Why isn't my (right) camera inspector isn't as big as the other one?
!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
it saids i dont have an sdk and i have an sdk and mono
Sorry I don't do either VSCode or Mac so I can't help you further with that other than to say go through each of the steps shown very very carefully
dang
So I want my player to instantly get some small speed when it starts to move. But how do I do it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Control : MonoBehaviour
{
private Rigidbody rb;
private float SpeedAdd = 200f;
private float SpeedMax = 60f;
// Start is called before the first frame update
void MoveLeft()
{
rb.AddForce(-transform.right * 200f);
if (Mathf.Abs(rb.velocity.x) < 5f)
{
rb.velocity = new Vector3(rb.velocity.x * -1.2f, rb.velocity.y, rb.velocity.z);
Debug.Log($"The current velocity: {rb.velocity.x}");
}
}
void MoveRight()
{
rb.AddForce(transform.right * 200f);
}
void Jump()
{
rb.AddForce(transform.up * 1000f);
}
void NotMoving_SlowDown()
{
rb.velocity = new Vector3(rb.velocity.x * 0.88f, rb.velocity.y, rb.velocity.z);
Debug.Log($"Not pressing D. Current in right velocity: {rb.velocity.x}, making closer to 0...");
}
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.A))
{
MoveLeft();
}
if (Input.GetKey(KeyCode.D))
{
MoveRight();
}
if (!Input.GetKey(KeyCode.A) & !Input.GetKey(KeyCode.D))
{
//rb.velocity = new Vector3(0, 0, 0);
NotMoving_SlowDown();
}
if (Input.GetKey(KeyCode.Space))
Jump();
Debug.Log(rb.velocity);
}
}
I think I tried all logical ways I could make it
actually, now i see some normal renderers have the same issue
Just add an initial speed variable and modify your MoveRIght() and MoveLeft() methods
rb.AddForce(-transform.right * SpeedAdd);
You probably have static batching enabled
i do. cant i have static batching enabled, and also have this code running?
You can also have a flag to check if the player started/stopped moving and add whatever logic you're looking for from there @frank flare
The mesh produced by static batching is not marked as readable
aight, thanks
vertx can you help me
I'm following a tutorial
not code question
this is urp camera, the inspector is different
Now I have changed it
if (Mathf.Abs(rb.velocity.x) < 10f)
{
rb.AddForce(-transform.right * 2000f);
Debug.Log($"The current velocity: {rb.velocity.x}");
}
but when I move right and then left it moves kinda buggy and I want it to stop faster
private bool isMoving = false;
I want it to still slide left a bit, but less
so the game will be smooth
if (!isMoving)
{
rb.velocity = new Vector3(-SpeedAdd, rb.velocity.y, rb.velocity.z);
isMoving = true;
}
else
{
rb.AddForce(transform.right * SpeedAdd);
}
Adding logic like this can help
Are there any ways to create a pixelated/retro style for BiRP?
maybe making it closer to the 0, 0, 0 velocity in case if the direction it's moving is right better?
something like that
rb.velocity = new Vector3(rb.velocity.x * 0.88f, rb.velocity.y, rb.velocity.z);
How can I get Debug.Log to show atleast like 2 decimal points from math equations?
Do I need to do the math before as a float them add the float to the log? Or can I do it all with the Debug.Log line?
either will work. to specify the number of decimals use .ToString("Nx") where x is the numer of decimals you want
As the smort person I am, I was tryna mash 2 ints into a float
yep, that will break for sure
aspectRatio.ToString("N2")?
I'm trying to think about the best way to go about implementing dialogue into my game. I've done calculations and the amount of dialogue in the game in its entirety is probably going to be roughly around 15,000 pieces. I've seen some places which say to use scriptable objects for storing text, but given the absolute size of the dialogue I need, I feel like a text based approach would be better.
Though, I'm not entirely certain how to go about this. I certainly don't want to search through the files every single time a piece of dialogue needs to be summoned. But I also don't know if it's common practice / best to load that much dialogue in at runtime through dictionaries or lists of some sort and leave it just sitting there in memory
Any tips? / common practice ways to go about this?
I've seen popular assets making one with visual scripting, one of which I got from humble bundle so that's an option, but otherwise I'd do SOs with a dialogue binary tree
SOs with a dialogue binary tree?
or any type of node based data struct
on it's own, no. in a Debug.Log, yes
presuming aspectRatio is a float
https://assetstore.unity.com/packages/tools/behavior-ai/dialogue-system-for-unity-11672
Ah, this is the asset I'm talking about. I think I got it off of a humble bundle, but that's quite an expensive asset.
Disco Elysium uses it I heard
Seems like a waste of money. I just want to see approaches of how I would efficiently retrieve the dialogue I need
there isn't going to be much dialogue choices in the game anyway
not to that extent
sounds like a job for a proper database
if it's just not choice based then just giving every npc some dialogue by inserting an SO into them seems viable enough
problem with that approach is that all the text will be loaded at startup
Well, all my characters are randomly generated with personality types, and each one has like 500 lines of dialogue
is there a way to only play the last part on an animation depending on what hte last animation was?
Not sure if Inky can do that but its worth checking out
Its also free
You can set up the specific transition either in the animator or trough code
Can I change the name of a prefab as its instantiated?
after instantiation, yes
https://docs.unity3d.com/ScriptReference/Object-name.html
Name of the spawned object I assume, as changing the prefab name wouldnt make sense
right
{
GameObject g = new GameObject("X:"+x+" Y:"+y);
g.transform.position = new Vector3(x -(horizontal - 0.5f), y -(vertical - 0.5f));``` is what I had
but im tryna make it load a prefab instead
then get its name
this seems like itd mean i have to create a new gameobject for every tile
When I press a or d then unpress d and press a it seem to make a bigger force. Why?
if (rb.velocity.x > 0)
{
rb.AddForce(-transform.right * 800f);
}
else if (Mathf.Abs(rb.velocity.x) < 10f)
{
rb.AddForce(-transform.right * 650f);
Debug.Log($"a The current velocity: {rb.velocity.x}");
}
else if (Mathf.Abs(rb.velocity.x) < 40f)
{
rb.AddForce(-transform.right * 800f);
Debug.Log($"b The current velocity: {rb.velocity.x}");
}
I dont know where tiles comes into this, your question was about changing the name.
Sorry, should have been more specific
tryna make a 2d grid
{
public Sprite sprite;
public float [,] grid;
public int columns, rows, vertical, horizontal;
public bool render;
// Start is called before the first frame update
void Start()
{
render = false;
Debug.Log("Screen Width : " + Screen.width);
vertical = (int)Camera.main.orthographicSize;
horizontal = vertical * Screen.width / Screen.height;
columns = horizontal * 2;
rows = vertical * 2;
grid = new float[columns, rows];
}
void Update()
{
for (int i = 0; i < columns; i++)
{
for (int j = 0; j < rows; j++)
{
while (render == true)
{
spawnTile(i, j, grid[i,j]);
bool render = false;
}
}
}
}
private void spawnTile(int x, int y, float value)
{
GameObject g = new GameObject("X:"+x+" Y:"+y);
g.transform.position = new Vector3(x -(horizontal - 0.5f), y -(vertical - 0.5f));
var s = g.AddComponent<SpriteRenderer>();
s.sprite = sprite;
s.color = new Color(value, value, value);
}
}``` this is the version that makes a new gameobject for each grid tile
{
public Sprite sprite;
public GameObject g;
public float [,] grid;
public bool render;
public int columns, rows, vertical, horizontal, size;
public float aspectRatio;
void Start()
{
//Debug.Log Shit
Debug.Log("Fetching screen dimensions...");
Debug.Log("Screen resolution : " + Screen.width + "x" + Screen.height);
aspectRatio = (Screen.width / Screen.height);
Debug.Log("Aspect ratio : " + aspectRatio);
//Mathy Shit
vertical = (int)Camera.main.orthographicSize;
horizontal = vertical * Screen.width / Screen.height;
columns = horizontal * size;
rows = vertical * size;
grid = new float[columns, rows];
for (int i = 0; i < columns; i++)
{
for (int j = 0; j < rows; j++)
{
spawnTile(i, j, grid[i,j]);
}
}
}
private void spawnTile(int x, int y, float value)
{
GameObject g = g("X:"+x+" Y:"+y);
g.transform.position = new Vector3(x -(horizontal - 0.5f), y -(vertical - 0.5f));
if (render == true)
{
var s = g.AddComponent<SpriteRenderer>();
s.sprite = sprite;
s.color = new Color(value, value, value);
}
}
}``` This ones the one im tryna have use prefabs
Oh, those are a little large
my bad
im trying to code, but i have this issue, im sorry if this is an incredibly dumb question but i genuinely dont know what im doing wrong
'{' under the class i think
I tried putting
rb.velocity.x > 0.1f
instead of
rb.velocity.x > 0
but I don't see much difference, if there is any
so this
GameObject g = g("X:"+x+" Y:"+y);
needs to be
GameObject g1 = Instantiate(g);
check the docs for the correct signature
Does anyone know how I can deserialize a JSON file?
I do not want to deserialize it to an object, I just want to get some values out of the file
ty 🥹
a JSON file is already serialized, that is what JSON is
Oh right I meant deserialize it
you could read the file as a string and do string searches on it
Also configure your !ide while you're at it. Your IDE should be pointing out these errors
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
so parse it yourself in effect
is there nothing native in Unity, like the json package in Python for example? I know there is System.Text.Json but it isn't part of Unity
Any reason you want to do this? You're still gonna have to allocate for the strings if you search manually
you said you did not want to deserialize to an object
That sounds way too complicated if there are already implementations of it for C#
I have certain fields I want to get from the file instead of a full object
Just get the full object, grab the values you want and ignore the rest.
Assets/gridManagerAlt.cs(41,24): error CS0165: Use of unassigned local variable 'g'
String search here is your only other option, and it is a terrible option to do.
You can new GameObject and it will spawn one in your scene. This looks like what you were trying to do tbh.
what? show code
up here
though has since been slightly tweaked per bawsi's suggestion
but you've changed it and made a mistake
Do you guys know if I can include Newtonsoft.JSON? Cause I saw that Unity supports that
is it a package I can include from the PackageManager?
am i not able to somehow drag the text into the score text script? the person whose tutorial im following does it without any issues
yes, but that will not address your original question
Note (Text) is not (TextMeshPro - Text)
ohhhh makes sense
Ok thanks
There are some free assets available on the asset store, I use TotalJSON and it works good enough, but getting the whole object and grabbing the values you want is a completely fine option too
I just installed Newtonsoft.Json and I think I'll use that
but thank you anyways
Well
thats 1 step foward
for some reason
its only created 2 tho
ones huge
the other doesnt seem to render anything
Oh
the other has no sprite renderer
setting the sprites pixels per unit lower just made it bigger?
It only has issues when I set render to true
UnityEngine.GameObject:AddComponent<UnityEngine.SpriteRenderer> ()
gridManagerAlt:spawnTile (int,int,single) (at Assets/gridManagerAlt.cs:45)
gridManagerAlt:Start () (at Assets/gridManagerAlt.cs:33)
gridManagerAlt.spawnTile (System.Int32 x, System.Int32 y, System.Single value) (at Assets/gridManagerAlt.cs:46)
gridManagerAlt.Start () (at Assets/gridManagerAlt.cs:33)```
Only makes one clone
again post your latest code
private void spawnTile(int x, int y, float value)
{
GameObject g10 = Instantiate(g);
g.transform.position = new Vector3(x -(horizontal - 0.5f), y -(vertical - 0.5f));
if (render == true)
{
var s = g.AddComponent<SpriteRenderer>();
s.sprite = sprite;
s.color = new Color(value, value, value);
}
}
}
Do I have to give it a new name everytime spawnTile is run?
no that wouldnt make sense
no, but look at the objects you are trying to change
ah
look at this
GameObject g10 = Instantiate(g);
g.transform.position = new Vector3(x -(horizontal - 0.5f), y -(vertical - 0.5f));
Do you want to move the NEW GO or the Original?
the new
so do that
original is never loaded
though this part works fine
no it doesn't
Is there a way to make it so an input starts being set to 0 on a condition?
you are missing the point
GameObject g10 = Instantiate(g);
g.transform.position = new Vector3(x -(horizontal - 0.5f), y -(vertical - 0.5f));
changes the position of the original
you need
GameObject g10 = Instantiate(g);
g10.transform.position = new Vector3(x -(horizontal - 0.5f), y -(vertical - 0.5f));
to change the position of the new object
and the same is true of you add component
runModifierVert = _runModifier * Input.GetAxis("Running") * Input.GetAxis("Vertical") * baseSpeed * (stamina > 0? 1 : 0);
I have this method here for making the player accelerate and deaccelerate gradually if they hold down or release the "Running" button but I want it to gradually decrease as if the key was released if the stamina hits 0
rn * (stamina > 0? 1 : 0) just instantly stops movement
what is the result of anything when you multiply by zero?
wrong
Thats
progress
Renders normally again
though I cant for the life of me guess why it wont line up with the Camera
And its
waaaay bigger than the camera
IEnumerator LerpFunction(Color endValue, float duration)
{
float time = 0;
Color startValue = materialToChange.color;
while (time < duration)
{
materialToChange.color = Color.Lerp(startValue, endValue, time / duration);
time += Time.deltaTime;
yield return null;
}
materialToChange.color = endValue;
}
I'm confused about this code (it's apparently a successful Color.Lerp)
How does the Color.Lerp know which 2nd colour to lerp with, if its defined afterwards?
the "endValue" variable isn't defined until the end in "materialToChange.color = endValue;"
no?
What
endValue is passed as a parameter into LerpFunction
it is defined from the very beginning
yeah but its only defined as a color
is there a default color or smth
its not given any values like Color.White or even RGB floats
Do you know how functions work?
void DoStuff(Color color)
{
...
}
...
Color myColor = new Color(0.5f, 0.5f, 1f, 1f);
DoStuff(myColor);
yeah but its defined as materialToChange.color = endValue; at the end
in your code example you gave it value at the end, thats what i expected
its not given any value in the code i sent except for materialToChange.color
which is just the Color.Lerp that already uses oit
I have no idea what you mean by that.
This line is just assigning endValue to the field/property color of materialToChange
endValue is being assigned the moment you call the function from elsewhere
what?
IEnumerator LerpFunction(Color endValue, float duration)
ohh wait i think i see now
so materialToChange.color = endValue; means that materialToChange.color is a Color
still though, i don't understand the Color.Lerp
if endValue is defined as a Color and nothing else
wouldnt the Color.Lerp be (materialToChange.color, Color, Time.deltaTime);
or am i wrong
very wrong
alright walk me through how it works
Read it again
i understand how Color.Lerp in general works i just dont get this specific example because the things dont have values (from my perspective)
why do you think that?
it says Color.Lerp(startValue, endValue, time/duration);
for each color channel, the return value=
start.channel *(1-t) +end.channel *t
but the variables aren't defined as floats or anything
They literally are defined as a Color
color has three floats (or four if you needs a)
You don't pass the type into a function if that's what you mean, just the variable name
Look at this
Color startValue = materialToChange.color;
while (time < duration)
{
materialToChange.color = Color.Lerp(startValue, endValue, time / duration);
time += Time.deltaTime;
yield return null;
}
The start value is the original materialToChange.color Color
The end value (i.e. the Color to go to) is passed IN as a parameter of the method
it's that simple
IEnumerator LerpFunction(Color endValue, float duration) // Defining endValue and duration
Color startValue = materialToChange.color; // Defining startValue
float time = 0; // Defining time
materialToChange.color = Color.Lerp(startValue, endValue, time / duration); // The Lerp
hows this work if startValue isnt given actual value yet and neither is endValue (besides being called a color)
sorry didnt read your thing i was writing this
ill read it now
ohhh right yeah
okay so that has value then
still don't get endValue tho
how do you call this method?
It's passed when you call the method. That's how method parameters work.
Dear lord, please go through a C# course
so it gains the same value as the startValue?
No.
so... when you call the function.. it gains value?
public void method(int x){}
method(10);
```so what is the value of x in the method
Do it again
Then, pay more attention, because damn this is the second tutorial
so when the LerpFunction is called
it'll say like...
LerpFunction(Color.White, 5f)
defining the duration and endValue?
it says it's not assigned, but it clearly is? or am i dumb
i do take courses its just i'm an idiot sometimes lol
im actually way ahead
im on the Lerp course
Search the scene for other instances of the script
Configure your !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
ok hold on
And neither of those are searching the scene
im getting used to unity im trying i suck at it 😭
Go through a pure C# course first, since your problems are related to how basic programming works.
Make sure you understand everything more or less and then start with Unity, otherwise you're gonna have a massive amount of basic issues not even related to Unity along the way.
Heard that w3schools has a good C# course, so here you go:
https://www.w3schools.com/cs/index.php
does this not play the end of the animation, like the last frame?
cmon man i just made a mistake im a lil forgetful
fair enough its a simple mistake but i know C#
...relatively
....the basics
You all humour this, don't get upset when you're stuck explaining the basics.
I doubt that
you know everyone in here keeps doing that, doubting I have any knowledge at all :/
but i digress
thank you for the help
and advice
Well, the doubting doesn't come from nowhere, you may have some amount of knowledge but not knowing how a function / passing params works is a clear indicator that you do not know enough yet.
yeah thats fair
Should, but my hunch is that you'd rather try 0.999f in case there's some weirdness about starting a clip when it's over
Play() has some quirks to it and notably skips the animator state machine, so you may prefer to have a "crouched" state with its own clip instead
what are the main uses for Destroy
what even is this question xd
bro what even are your answers ngl
im just asking what Destroy is commonly used for, like in what context or scenario its useful
you kill a enemy, what happens then?
so its used to clean up unnecessary objects?
it's removeing a GameObject, component or asset
imagine having hack&slash game
where you have 200 enemies, shoot projectiles
why would you keep alive(dead) enemy/used bullet particles objects on the scene
i dunno, detail?
(unless we're talking about object pooling but im simplyfing)
keep the corpses there
alright so its used for cleaning up unnecessary objects
cool
any other uses?
you can just google it in 10 seconds
im respecting my time, won't be your "google" 😛
I would suggest object pooling if you want to reuse stuff without destroying it. For example bullets and multiple types of the same enemy
that's what i said later
Anyone know how to work with AR?
Apologies just missed it
some poeple probably do know, don't ask to ask, also #🤯┃augmented-reality
hey, i have posted about my problem. just looking for any one who knows about this stuff, im just desperate lol
then dont cross-post
Is there an OnValidate that also happens when a child object count was increased? For a CircularLayoutGroup that I made
Sounds tricky, but maybe some subscription model you can set up
that's nasty ig
it would mostly be the object you're adding sending a callback to the parent
any ideas for this?
instead of the parent continuously checking for new children
could be some interface unity has but idk
the character looks fine though
unless that sprite was like supposed to be 4k
actually, i remember i can check what unity done with their layout groups, I might get something
why not just inherit from unity's LayoutGroup if you want the class to behave like one?

