46
General / Re: Can't change shape's attributes outside of int main()
« on: February 14, 2024, 01:00:07 am »
Glad you got it to work!
First thing to note is that SFML objects shouldn't be global. It's not clear whether you mean this or not.
e.g. this is BAD:
It's usually better to create them and then pass them:
You don't need to pass objects back if you're using them temporarily:
With all that said, another thing to consider is that SFML needs to be included before using an object so, if you're doing something in a separate file, you'll likely need to include SFML headers from that file too.
First thing to note is that SFML objects shouldn't be global. It's not clear whether you mean this or not.
e.g. this is BAD:
sf::RenderWindow window;
int main()
{
}
The objects should be created inside the main function:int main()
{
}
int main()
{
sf::RenderWindow window;
}
It's still okay to create an object elsewhere as long as it still called by main:{
sf::RenderWindow window;
}
sf::RenderWindow* createRenderWindow()
{
sf::RenderWindow* pWindow = new sf::RenderWindow;
return pWindow;
}
int main()
{
sf::RenderWindow* pWindow = createRenderWindow();
}
Note that a pointer was used here for simplicity but this is not the safest way to do it. Use a smart pointer if you do it this way.{
sf::RenderWindow* pWindow = new sf::RenderWindow;
return pWindow;
}
int main()
{
sf::RenderWindow* pWindow = createRenderWindow();
}
It's usually better to create them and then pass them:
void createRenderWindow(sf::RenderWindow& window)
{
window.create(sf::VideoMode(960u, 540u), "");
}
int main()
{
sf::RenderWindow window;
createRenderWindow(window);
}
{
window.create(sf::VideoMode(960u, 540u), "");
}
int main()
{
sf::RenderWindow window;
createRenderWindow(window);
}
You don't need to pass objects back if you're using them temporarily:
void loadAFontButThenThrowItAway()
{
sf::Font font;
font.loadFromFile("fonts/arial.ttf"); // I am not checking whether it loads or not for simplicity and since it does not really matter here but you should always do that!
}
int main()
{
loadAFontButThenThrowItAway();
}
{
sf::Font font;
font.loadFromFile("fonts/arial.ttf"); // I am not checking whether it loads or not for simplicity and since it does not really matter here but you should always do that!
}
int main()
{
loadAFontButThenThrowItAway();
}
With all that said, another thing to consider is that SFML needs to be included before using an object so, if you're doing something in a separate file, you'll likely need to include SFML headers from that file too.